package websocket import ( "net/http" "git.loafle.net/commons/server-go" "github.com/valyala/fasthttp" ) type ServerHandler interface { server.ServerHandler OnError(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx, status int, reason error) RegisterServlet(path string, servlet Servlet) Servlet(path string) Servlet CheckOrigin(ctx *fasthttp.RequestCtx) bool } type ServerHandlers struct { server.ServerHandlers servlets map[string]Servlet } func (sh *ServerHandlers) Init(serverCtx server.ServerCtx) error { if err := sh.ServerHandlers.Init(serverCtx); nil != err { return err } if nil != sh.servlets { for _, servlet := range sh.servlets { if err := servlet.Init(serverCtx); nil != err { return err } } } return nil } func (sh *ServerHandlers) Destroy(serverCtx server.ServerCtx) { if nil != sh.servlets { for _, servlet := range sh.servlets { servlet.Destroy(serverCtx) } } sh.ServerHandlers.Destroy(serverCtx) } func (sh *ServerHandlers) OnPing(msg string) error { return nil } func (sh *ServerHandlers) OnPong(msg string) error { return nil } func (sh *ServerHandlers) OnClose(code int, text string) error { return nil } func (sh *ServerHandlers) OnError(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx, status int, reason error) { ctx.Response.Header.Set("Sec-Websocket-Version", "13") ctx.Error(http.StatusText(status), status) } func (sh *ServerHandlers) RegisterServlet(path string, servlet Servlet) { if nil == sh.servlets { sh.servlets = make(map[string]Servlet) } sh.servlets[path] = servlet } func (sh *ServerHandlers) Servlet(path string) Servlet { var servlet Servlet if path == "" && len(sh.servlets) == 1 { for _, s := range sh.servlets { servlet = s } } else if servlet = sh.servlets[path]; nil == servlet { return nil } return servlet } func (sh *ServerHandlers) CheckOrigin(ctx *fasthttp.RequestCtx) bool { return true } func (sh *ServerHandlers) Validate() error { if err := sh.ServerHandlers.Validate(); nil != err { return err } return nil }