acceptor.go 1.7 KB

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