aboutsummaryrefslogtreecommitdiff
path: root/pkg/ext/router.go
blob: 8b9a31090bef2036a018bb43cae4e6e81fd6ad0a (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
52
package ext

import (
	"net/http"

	"github.com/gorilla/mux"
)

type (
	Router struct {
		middlewares []Middleware
		router      *mux.Router
	}
	Middleware          func(next http.HandlerFunc) http.HandlerFunc
	ErrorRequestHandler func(w http.ResponseWriter, r *http.Request) error
)

func NewRouter(nestedRouter *mux.Router) *Router {
	return &Router{
		router: nestedRouter,
	}
}

func (r *Router) AddMiddleware(middleware Middleware) {
	r.middlewares = append(r.middlewares, middleware)
}

func wrapError(next ErrorRequestHandler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		if err := next(w, r); err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			InternalServerError(w, err)
		}
	}
}

func (r *Router) run(next ErrorRequestHandler) http.HandlerFunc {
	return func(w http.ResponseWriter, re *http.Request) {
		req := wrapError(next)
		for _, r := range r.middlewares {
			req = r(req)
		}
		req(w, re)
	}
}

func (r *Router) GET(path string, handler ErrorRequestHandler) {
	r.router.HandleFunc(path, r.run(handler)).Methods("GET")
}
func (r *Router) POST(path string, handler ErrorRequestHandler) {
	r.router.HandleFunc(path, r.run(handler)).Methods("POSt")
}