aboutsummaryrefslogtreecommitdiff
path: root/pkg/ext/router.go
blob: 74f0a95f468cb3a484bdfa17a27e6085c35729a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
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))
}