lens @ 417041797674319485bea96cb38489670ff3b2ef

 1package ext
 2
 3import (
 4	"net/http"
 5
 6	"github.com/gorilla/mux"
 7)
 8
 9type (
10	Router struct {
11		middlewares []Middleware
12		router      *mux.Router
13	}
14	Middleware          func(next http.HandlerFunc) http.HandlerFunc
15	ErrorRequestHandler func(w http.ResponseWriter, r *http.Request) error
16)
17
18func NewRouter(nestedRouter *mux.Router) *Router {
19	return &Router{
20		router: nestedRouter,
21	}
22}
23
24func (r *Router) AddMiddleware(middleware Middleware) {
25	r.middlewares = append(r.middlewares, middleware)
26}
27
28func wrapError(next ErrorRequestHandler) http.HandlerFunc {
29	return func(w http.ResponseWriter, r *http.Request) {
30		if err := next(w, r); err != nil {
31			w.WriteHeader(http.StatusInternalServerError)
32			InternalServerError(w, err)
33		}
34	}
35}
36
37func (r *Router) run(next ErrorRequestHandler) http.HandlerFunc {
38	return func(w http.ResponseWriter, re *http.Request) {
39		req := wrapError(next)
40		for _, r := range r.middlewares {
41			req = r(req)
42		}
43		req(w, re)
44	}
45}
46
47func (r *Router) GET(path string, handler ErrorRequestHandler) {
48	r.router.HandleFunc(path, r.run(handler)).Methods("GET")
49}
50func (r *Router) POST(path string, handler ErrorRequestHandler) {
51	r.router.HandleFunc(path, r.run(handler)).Methods("POSt")
52}