接口全览
func Handler(c *gin.Context) {
fmt.Println("进入函数")
token := module.WsGetTokenFromHeader(c.Request.Header)
fmt.Println(token)
stuNum := dao.Redis.Get(token).Val()
toStuNum := c.Query("toStuNum")
if stuNum == toStuNum {
c.JSON(http.StatusOK, gin.H{
"status": 203,
"msg": "自己无法与自己建立沟通",
})
return
}
conn, err := (&websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
Subprotocols: []string{token},
}).Upgrade(c.Writer, c.Request, nil)
if err != nil {
http.NotFound(c.Writer, c.Request)
return
}
client := &models.Client{
ID: createID(stuNum, toStuNum),
SendID: createID(toStuNum, stuNum),
FromUsername: stuNum,
ToUsername: toStuNum,
Socket: conn,
Send: make(chan []byte),
}
mux.Lock()
models.Manager.Register <- client
mux.Unlock()
go client.Read()
go client.Write()
go models.BatchRead(toStuNum, stuNum)
}
接口切片
如果前端使用Sec-WebSocket-Protocol字段传递token的话会引发websocket刚连接上就断开的问题 届时需要在Upgrader添加
Subprotocols: []string{token},
以建立连接
websocket升级
conn, err := (&websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
Subprotocols: []string{token},
}).Upgrade(c.Writer, c.Request, nil)
if err != nil {
http.NotFound(c.Writer, c.Request)
return
}
|