1 回答
TA贡献1844条经验 获得超8个赞
因为网络连接被 nhooyr websocket 库从 net/http 服务器劫持,所以在c.Request.Context()处理程序返回之前不会取消上下文。
调用CloseRead以获取在连接关闭时取消的上下文。在循环中使用该上下文。
var GetDriverLocations = func(c *gin.Context) {
wsoptions := websocket.AcceptOptions{InsecureSkipVerify: true}
wsconn, err := websocket.Accept(c.Writer, c.Request, &wsoptions)
if err != nil {
return
}
defer wsconn.Close(websocket.StatusInternalError, "")
ctx := wsconn.CloseRead(c.Request.Context())
driverLocation := &models.DriverLocation{}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
case <-ctx.Done():
return
}
coords, err := driverLocation.GetDrivers()
if err != nil {
break
}
err = wsjson.Write(c.Request.Context(), wsconn, &coords)
if err != nil {
break
}
}
}
- 1 回答
- 0 关注
- 135 浏览
添加回答
举报
