Gin框架結合gorilla實現websocket


gin和gorilla結合創建websocket簡單實用,引入gorilla庫:

go get -u github.com/gorilla/websocket

使用了mod則更新下依賴關系:

go mod tidy

1.在controller下面新建一個websocket.go,作為實現服務端業務邏輯部分:

package controllers

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "github.com/gorilla/websocket"
    "net/http"
    "time"
)

var upGrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true
    },
}

func WsHandle(c *gin.Context) {
    //升級get請求為webSocket協議
    ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
    if err != nil {
        c.Writer.Write([]byte(err.Error()))
        return
    }
    defer ws.Close()
    for {
        //讀取ws中的數據
        mt, message, err := ws.ReadMessage()
        if err != nil {
            c.Writer.Write([]byte(err.Error()))
            break
        }
        fmt.Println("client message " + string(message))
        //寫入ws數據
        err = ws.WriteMessage(mt, []byte(time.Now().String()))
        if err != nil {
            break
        }
        fmt.Println("system message " + time.Now().String())
    }
}

2.在router.go路由器中添加websocket連接請求操作的路由:

//websocket測試
router.GET("/wx", controllers.WsHandle)

3.在static下面創建websocket.html文件操作請求信息:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<table>
    <tr><td valign="top" width="50%">
            <p>點擊啟動按鈕創建websocket連接<br/>
               點擊發送按鈕可以發送任意消息給服務器<br/>
               點擊關閉按鈕斷開websocket連接
            </p>
            <form>
                <button id="open">啟動</button>
                <button id="close">關閉</button>
                <input id="input" type="text" value="Hello golang!">
                <button id="send">發送</button>
            </form>
        </td><td valign="top" width="50%">
            <div id="output"></div>
        </td></tr></table>
</body>
</html>
<script>
        window.addEventListener("load", function(evt) {
            var output = document.getElementById("output");
            var input = document.getElementById("input");
            var ws;
            var print = function(message) {
                var d = document.createElement("div");
                d.innerHTML = message;
                output.appendChild(d);
            };
            document.getElementById("open").onclick = function(evt) {
                if (ws) {
                    return false;
                }
                ws = new WebSocket("ws://localhost:8888/ws");
                ws.onopen = function(evt) {
                    print("連接websocket");
                }
                ws.onclose = function(evt) {
                    print("CLOSE");
                    ws = null;
                }
                ws.onmessage = function(evt) {
                    print("收到消息: " + evt.data);
                }
                ws.onerror = function(evt) {
                    print("ERROR: " + evt.data);
                }
                return false;
            };
            document.getElementById("send").onclick = function(evt) {
                if (!ws) {
                    return false;
                }
                print("發送消息: " + input.value);
                ws.send(input.value);
                return false;
            };
            document.getElementById("close").onclick = function(evt) {
                if (!ws) {
                    return false;
                }
                ws.close();
                return false;
            };
        });
</script>

4.請求操作測試:

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM