overflow_server_app/server/server.go
2017-08-23 18:19:21 +09:00

45 lines
931 B
Go

package server
import (
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
)
type Server interface {
Handler(ctx *fasthttp.RequestCtx)
Route(method, path string, handler RequestHandler)
SetContextValue(key interface{}, value interface{})
}
type server struct {
ctx *ServerContext
router *fasthttprouter.Router
}
func New() Server {
s := &server{}
s.router = fasthttprouter.New()
s.ctx = &ServerContext{}
return s
}
func (s *server) SetContextValue(key interface{}, value interface{}) {
s.ctx.setValue(key, value)
}
func (s *server) Handler(ctx *fasthttp.RequestCtx) {
s.router.Handler(ctx)
}
func (s *server) Route(method, path string, handler RequestHandler) {
s.router.Handle(method, path, s.wrapHandler(handler))
}
func (s *server) wrapHandler(handler RequestHandler) fasthttp.RequestHandler {
return fasthttp.RequestHandler(func(ctx *fasthttp.RequestCtx) {
handler(s.ctx, ctx)
})
}