slowwildwshandler.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. package handler
  2. import (
  3. "net/http"
  4. "slowwildws/internal/logic"
  5. "slowwildws/internal/server"
  6. "slowwildws/internal/svc"
  7. "github.com/gorilla/websocket"
  8. xhttp "github.com/zeromicro/x/http"
  9. )
  10. func SlowwildwsHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
  11. return func(w http.ResponseWriter, r *http.Request) {
  12. var responseHeader http.Header
  13. if protocol := r.Header.Get("Sec-Websocket-Protocol"); protocol != "" {
  14. responseHeader = http.Header{
  15. "Sec-Websocket-Protocol": []string{protocol},
  16. }
  17. }
  18. upgrade := websocket.Upgrader{}
  19. conn, err := upgrade.Upgrade(w, r, responseHeader)
  20. if err != nil {
  21. xhttp.JsonBaseResponseCtx(r.Context(), w, err)
  22. return
  23. }
  24. // 初始化一个连接服务
  25. connServer := svcCtx.WsServer.InitConn(r.Context(), conn, svcCtx.Config)
  26. // 添加连接信息到连接池
  27. svcCtx.WsServer.AddConn(connServer, r.Context())
  28. // 开启协程校验心跳,保持连接
  29. go connServer.Keepalive()
  30. // 开启协程处理消息
  31. go func(svcCtx *svc.ServiceContext, r *http.Request, connServer *server.ConnectionServer) {
  32. l := logic.NewConnectionLogic(r.Context(), svcCtx)
  33. l.HandlerConn(connServer)
  34. }(svcCtx, r, connServer)
  35. }
  36. }