在gin框架下
导入包
"github.com/gorilla/websocket"
r.GET("/test", test)
//webSocket请求haha 返回heihei
func test(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) == "haha" {message = []byte("heihei")}//写入ws数据err = ws.WriteMessage(mt, message)if err != nil {break}}
}
在谷歌浏览器里添加一个插件(Simple WebSocket Client),来测试自己写的api,
URL: ws://127.0.0.1:8081/test
//前后端交互的小案例
上代码:
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 },
} func test(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) == "haha" { message = []byte("heihei") } //写入ws数据err = ws.WriteMessage(mt, message) if err != nil { break } }
} func main() { bindAddress := "localhost:8081" r := gin.Default() r.GET("/test", test) r.Run(bindAddress)
}
js代码:
<script>
var ws = new WebSocket("ws://localhost:8081/test");
//连接打开时触发
ws.onopen = function(evt) { console.log("Connection open ..."); ws.send("Hello WebSockets!");
};
//接收到消息时触发
ws.onmessage = function(evt) { console.log("Received Message: " + evt.data);
};
//连接关闭时触发
ws.onclose = function(evt) { console.log("Connection closed.");
}; </script>