server-go/socket/web/server-handler.go

93 lines
2.0 KiB
Go
Raw Normal View History

2018-04-05 15:15:29 +00:00
package web
2018-04-04 04:01:26 +00:00
import (
"net/http"
"git.loafle.net/commons/server-go"
2018-04-05 15:15:29 +00:00
"git.loafle.net/commons/server-go/socket"
2018-04-04 04:01:26 +00:00
"github.com/valyala/fasthttp"
)
type ServerHandler interface {
2018-04-05 15:15:29 +00:00
socket.ServerHandler
2018-04-04 04:01:26 +00:00
OnError(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx, status int, reason error)
RegisterServlet(path string, servlet Servlet)
2018-04-04 16:51:34 +00:00
Servlet(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx) Servlet
2018-04-04 04:01:26 +00:00
CheckOrigin(ctx *fasthttp.RequestCtx) bool
}
type ServerHandlers struct {
2018-04-06 00:28:42 +00:00
socket.ServerHandlers
2018-04-04 04:01:26 +00:00
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) 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
}
2018-04-04 16:51:34 +00:00
func (sh *ServerHandlers) Servlet(serverCtx server.ServerCtx, ctx *fasthttp.RequestCtx) Servlet {
path := string(ctx.Path())
2018-04-04 04:01:26 +00:00
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
}