package handler import ( "net/http" "slowwildws/internal/logic" "slowwildws/internal/server" "slowwildws/internal/svc" "github.com/gorilla/websocket" xhttp "github.com/zeromicro/x/http" ) func SlowwildwsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { var responseHeader http.Header if protocol := r.Header.Get("Sec-Websocket-Protocol"); protocol != "" { responseHeader = http.Header{ "Sec-Websocket-Protocol": []string{protocol}, } } upgrade := websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } conn, err := upgrade.Upgrade(w, r, responseHeader) if err != nil { xhttp.JsonBaseResponseCtx(r.Context(), w, err) return } // 初始化一个连接服务 connServer := svcCtx.WsServer.InitConn(r.Context(), conn, svcCtx.Config) // 添加连接信息到连接池 svcCtx.WsServer.AddConn(connServer, r.Context()) // 开启协程校验心跳,保持连接 go connServer.Keepalive() // 开启协程处理消息 go func(svcCtx *svc.ServiceContext, r *http.Request, connServer *server.ConnectionServer) { l := logic.NewConnectionLogic(r.Context(), svcCtx) l.HandlerConn(connServer) }(svcCtx, r, connServer) } }