acceptor.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. Acceptor(path string, sessMgr *peer.SessionManager)
  21. Stop(sessMgr *peer.SessionManager)
  22. }
  23. type wsAcceptor struct {
  24. server *http.Server
  25. logger *zap.Logger
  26. }
  27. func NewWsAcceptor(loggers *zap.Logger) WsAcceptor {
  28. return &wsAcceptor{logger: loggers}
  29. }
  30. func (ws *wsAcceptor) Acceptor(path string, sessMgr *peer.SessionManager) {
  31. http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
  32. c, upgradeErr := upgrader.Upgrade(w, r, nil)
  33. if upgradeErr != nil {
  34. ws.logger.Sugar().Errorf("upgrade http failed: %s", upgradeErr)
  35. return
  36. }
  37. sessMgr.Register <- peer.NewSession(newConnection(c, sessMgr))
  38. })
  39. }
  40. func (ws *wsAcceptor) Start(addr string, sessMgr *peer.SessionManager) error {
  41. urlObj, err := url.Parse(addr)
  42. if err != nil {
  43. return fmt.Errorf("websocket urlparse failed. url(%s) %v", addr, err)
  44. }
  45. if urlObj.Path == "" {
  46. return fmt.Errorf("websocket start failed. expect path in url to listen addr:%s", addr)
  47. }
  48. ws.Acceptor(urlObj.Path, sessMgr)
  49. ws.server = &http.Server{Addr: urlObj.Host}
  50. err = ws.server.ListenAndServe()
  51. if err != nil && err != http.ErrServerClosed {
  52. return fmt.Errorf("websocket ListenAndServe addr:%s failed:%v", addr, err)
  53. }
  54. return nil
  55. }
  56. func (ws *wsAcceptor) Stop(sessMgr *peer.SessionManager) {
  57. sessMgr.CloseAllSession()
  58. ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
  59. defer cancel()
  60. if err := ws.server.Shutdown(ctx); err != nil {
  61. ws.logger.Sugar().Errorf("server shutdown err:[%s]", err)
  62. }
  63. }