-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrouter.go
47 lines (39 loc) · 1.01 KB
/
router.go
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
package handlers
import (
"github.com/gorilla/mux"
"github.com/sirupsen/logrus"
)
type Router struct {
*mux.Router
middlewares []Middleware
}
func NewRouter(logger logrus.FieldLogger) *Router {
r := &Router{}
r.Router = mux.NewRouter()
r.Use(MiddlewareFunc(RequestIDMiddleware))
r.Use(NewLoggingMiddleware(logger))
return r
}
func New() *Router {
r := &Router{}
r.Router = mux.NewRouter()
r.Use(MiddlewareFunc(RequestIDMiddleware))
return r
}
func (r *Router) HandleFunc(pattern string, f HandlerFunc) *mux.Route {
for _, m := range r.middlewares {
f = m.Apply(f)
}
stdHandler := ToHTTPHandler(f)
return r.Router.Handle(pattern, stdHandler)
}
func (r *Router) Handle(pattern string, h Handler) *mux.Route {
return r.HandleFunc(pattern, h.ServeHTTP)
}
func (r *Router) Use(m Middleware) {
// Add at the beginning of the middleware stack
// The last middleware is called first
middlewares := r.middlewares
r.middlewares = append([]Middleware(nil), m)
r.middlewares = append(r.middlewares, middlewares...)
}