首先使用gin创建一个http服务
package main
import (
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
r.LoadHTMLFiles("index.html")
r.GET("/", func(c *gin.Context) {
c.HTML(200, "index.html", nil)
})
r.Run("localhost:12312")
}
使用到了一个index.html模板,用来做客户端测试websocket的,仅作为演示用
安装gorilla
go get github.com/gorilla/websocket
修改main.go
package main
import (
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
)
var wsupgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
func wshandler(w http.ResponseWriter, r *http.Request) {
conn, err := wsupgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("Failed to set websocket upgrade: %+v", err)
return
}
for {
t, msg, err := conn.ReadMessage()
if err != nil {
break
}
conn.WriteMessage(t, msg)
}
}
func main() {
r := gin.Default()
//websocket 请求使用 wshandler函数处理
r.GET("/ws", func(c *gin.Context) {
wshandler(c.Writer, c.Request)
})
r.LoadHTMLFiles("index.html")
r.GET("/", func(c *gin.Context) {
c.HTML(200, "index.html", nil)
})
r.Run("localhost:12312")
}
index.html 文件
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<h3>WebSocket Go</h3>
<pre id="output"></pre>
<script>
url = 'ws://localhost:12312/ws';
c = new WebSocket(url);
send = function(data){
$("#output").append((new Date())+ " ==> "+data+"\n")
c.send(data)
}
c.onmessage = function(msg){
$("#output").append((new Date())+ " <== "+msg.data+"\n")
console.log(msg)
}
c.onopen = function(){
setInterval(
function(){ send("ping") }
, 1000 )
}
</script>
</body>
</html>
效果图: