package overflow_gateway_websocket import ( "log" "git.loafle.net/overflow/overflow_gateway_websocket/clients" "git.loafle.net/overflow/overflow_gateway_websocket/websocket" "github.com/valyala/fasthttp" ) type () type Server interface { ListenAndServe(addr string) error HandleClient(pattern string, o *clients.Options) } type server struct { _option *Options _upgrader *websocket.Upgrader _handlers map[string]*clients.Options _clients map[string]clients.Client } func NewServer(o *Options) Server { s := &server{ _option: o.Validate(), _handlers: make(map[string]*clients.Options, 1), _clients: make(map[string]clients.Client, 100), } s._upgrader = &websocket.Upgrader{ ReadBufferSize: s._option.ReadBufferSize, WriteBufferSize: s._option.WriteBufferSize, HandshakeTimeout: s._option.HandshakeTimeout, } return s } func (s *server) onPush(cb OnPushFunc) { } func (s *server) onDisconnected(c clients.Client) { delete(s._clients, c.ID()) s._option.OnDisconnected(c) } func (s *server) onConnection(ctx *fasthttp.RequestCtx) { s._upgrader.Upgrade(ctx, nil, func(conn *websocket.Conn, err error) { if err != nil { log.Print("upgrade:", err) return } path := string(ctx.Path()) co, ok := s._handlers[path] if !ok { log.Printf("Path[%s] is not exist.", path) return } cid := s._option.IDGenerator(ctx) c := clients.New(cid, co, ctx, conn) s._clients[cid] = c s._option.OnConnection(path, c) }) } func (s *server) HandleClient(pattern string, o *clients.Options) { s._handlers[pattern] = o.Validate() } func (s *server) ListenAndServe(addr string) error { return fasthttp.ListenAndServe(addr, s.onConnection) }