deprecated_overflow_gateway.../server.go
crusader 67dbc5cd28 ing
2017-08-24 23:50:14 +09:00

80 lines
1.7 KiB
Go

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,
CheckOrigin: s._option.OnCheckOrigin,
}
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) {
path := string(ctx.Path())
s._upgrader.Upgrade(ctx, nil, func(conn *websocket.Conn, err error) {
if err != nil {
log.Print("upgrade:", err)
return
}
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)
}