package ext import ( "github.com/fasthttp/router" "github.com/valyala/fasthttp" ) type ( Router struct { middlewares []Middleware fastRouter *router.Router } Middleware func(next fasthttp.RequestHandler) fasthttp.RequestHandler ErrorRequestHandler func(ctx *fasthttp.RequestCtx) error ) func NewRouter(nestedRouter *router.Router) *Router { return &Router{ fastRouter: nestedRouter, } } func (self *Router) AddMiddleware(middleware Middleware) { self.middlewares = append(self.middlewares, middleware) } func wrapError(next ErrorRequestHandler) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { if err := next(ctx); err != nil { ctx.Response.SetStatusCode(500) InternalServerError(ctx, err) } } } func (self *Router) run(next ErrorRequestHandler) fasthttp.RequestHandler { return func(ctx *fasthttp.RequestCtx) { req := wrapError(next) for _, r := range self.middlewares { req = r(req) } req(ctx) } } func (self *Router) GET(path string, handler ErrorRequestHandler) { self.fastRouter.GET(path, self.run(handler)) } func (self *Router) POST(path string, handler ErrorRequestHandler) { self.fastRouter.POST(path, self.run(handler)) }