Go Gin使用Websocket

github地址:https://github.com/gin-gonic/gin

go get github.com/gin-gonic/gin

gorilla拥有很多类库,这次我们使用的是它的webSocket

go get github.com/gorilla/websocket
package main

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

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

//webSocket请求ping 返回pong  
func ping(c *gin.Context) {
    //升级get请求为webSocket协议
    ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
    if err != nil {
        return
    }
    defer ws.Close()
    for {
        //读取ws中的数据  
        mt, message, err := ws.ReadMessage()
        if err != nil {
            break
        }
        if string(message) == "ping" {
            message = []byte("pong")
        }
        //写入ws数据
        err = ws.WriteMessage(mt, message)
        if err != nil {
            break
        }
    }
}

func main() {
    bindAddress := "localhost:2303"
    r := gin.Default()
    r.GET("/ping", ping)
    r.Run(bindAddress)
}

前端js代码


你可能感兴趣的:(Go Gin使用Websocket)