-
Notifications
You must be signed in to change notification settings - Fork 0
/
mux.go
53 lines (44 loc) · 1.53 KB
/
mux.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
48
49
50
51
52
53
package mux
import (
"net/http"
"strings"
)
// Mux wraps the http.ServeMux and provides a mechanism for registering
// middleware
type Mux struct {
mux *http.ServeMux
mw []Middleware
}
// New will return an instance of a new Mux. The provided middleware will wrap
// every handler registered to the Mux.
func New(mw ...Middleware) *Mux {
return &Mux{
mux: http.NewServeMux(),
mw: mw,
}
}
// ServeHTTP satisfies the handler interface.
func (m *Mux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
m.mux.ServeHTTP(w, r)
}
// Handle will register the provided handler on the mux, wrapped in the provided
// middleware(s). Middleware is envoked from left to right per request, after
// any mux level middleware.
func (m *Mux) Handle(pattern string, handler http.Handler, mw ...Middleware) {
// handler specific middleware
handler = WrapMiddleware(mw, handler)
// mux middleware
handler = WrapMiddleware(m.mw, handler)
m.mux.Handle(pattern, handler)
}
// HandleFunc will register the provided handler function on the mux, wrapped in
// the provided middleware(s). Middleware is envoked from left to right per
// request, after any mux level middleware.
func (m *Mux) HandleFunc(pattern string, handler http.HandlerFunc, mw ...Middleware) {
m.Handle(pattern, handler, mw...)
}
// Group will register the provided handler under the prefix. The prefix must
// end with a trailing slash.
func (m *Mux) Group(prefix string, h http.Handler, mw ...Middleware) {
m.Handle(prefix, http.StripPrefix(strings.TrimSuffix(prefix, "/"), h), mw...)
}