acceptor.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package connect
  2. import (
  3. "context"
  4. "fmt"
  5. "go.uber.org/zap"
  6. "net/http"
  7. "net/url"
  8. "time"
  9. "github.com/gorilla/websocket"
  10. "git.bvbej.com/bvbej/base-golang/pkg/websocket/peer"
  11. )
  12. var upgrader = websocket.Upgrader{
  13. CheckOrigin: func(r *http.Request) bool {
  14. return true
  15. },
  16. }
  17. type wsAcceptor struct {
  18. server *http.Server
  19. logger *zap.Logger
  20. }
  21. func (ws *wsAcceptor) Start(addr string, sessMgr *peer.SessionManager, loggers *zap.Logger) error {
  22. urlObj, err := url.Parse(addr)
  23. if err != nil {
  24. return fmt.Errorf("websocket urlparse failed. url(%s) %v", addr, err)
  25. }
  26. if urlObj.Path == "" {
  27. return fmt.Errorf("websocket start failed. expect path in url to listen addr:%s", addr)
  28. }
  29. http.HandleFunc(urlObj.Path, func(w http.ResponseWriter, r *http.Request) {
  30. c, err := upgrader.Upgrade(w, r, nil)
  31. if err != nil {
  32. fmt.Println(err)
  33. return
  34. }
  35. sessMgr.Register <- peer.NewSession(newConnection(c, sessMgr))
  36. })
  37. ws.logger = loggers
  38. ws.server = &http.Server{
  39. Addr: urlObj.Host,
  40. Handler: nil,
  41. }
  42. err = ws.server.ListenAndServe()
  43. if err != nil && err != http.ErrServerClosed {
  44. return fmt.Errorf("websocket ListenAndServe addr:%s failed:%v", addr, err)
  45. }
  46. return nil
  47. }
  48. func (ws *wsAcceptor) Stop(sessMgr *peer.SessionManager) {
  49. sessMgr.CloseAllSession()
  50. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  51. defer cancel()
  52. if err := ws.server.Shutdown(ctx); err != nil {
  53. ws.logger.Error("server shutdown err", zap.Error(err))
  54. }
  55. }
  56. func init() {
  57. peer.RegisterAcceptor("ws", new(wsAcceptor))
  58. }