-
Notifications
You must be signed in to change notification settings - Fork 0
/
mount.go
42 lines (38 loc) · 1.04 KB
/
mount.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
package mount
import "net/http"
import "strings"
// New mount middleware.
func New(prefix string, i interface{}) func(http.Handler) http.Handler {
mw := middleware(i)
return func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
original := r.URL.Path
if s := strings.TrimPrefix(r.URL.Path, prefix); len(s) < len(r.URL.Path) {
r.URL.Path = s
mw(h).ServeHTTP(w, r)
r.URL.Path = original
} else {
h.ServeHTTP(w, r)
}
})
}
}
// Coerce into middleware.
func middleware(h interface{}) func(http.Handler) http.Handler {
switch h.(type) {
case func(w http.ResponseWriter, r *http.Request):
h := http.HandlerFunc(h.(func(w http.ResponseWriter, r *http.Request)))
return func(_ http.Handler) http.Handler {
return http.HandlerFunc(h)
}
case http.Handler:
h := h.(http.Handler)
return func(_ http.Handler) http.Handler {
return h
}
case func(h http.Handler) http.Handler:
return h.(func(h http.Handler) http.Handler)
default:
panic("invalid middleware")
}
}