-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
62 lines (49 loc) · 1.3 KB
/
middleware.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
54
55
56
57
58
59
60
61
62
package middleware
import (
"net/http"
"strings"
)
// Middleware is a composable http.HandlerFunc wrapper
type Middleware func(next http.HandlerFunc) http.HandlerFunc
// Compose http.HandlerFunc from Middleware array
func Compose(middlewareArr ...Middleware) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
if len(middlewareArr) == 0 {
return
}
hf := func(http.ResponseWriter, *http.Request) { /* noop */ }
lastI := len(middlewareArr) - 1
last, body := middlewareArr[lastI], middlewareArr[:lastI]
hf = last(hf)
for i := len(body) - 1; i >= 0; i-- {
hf = body[i](hf)
}
hf(rw, req)
}
}
// Post method filter
func Post(hf http.HandlerFunc) Middleware {
return filterMethod("POST", hf)
}
// Get method filter
func Get(hf http.HandlerFunc) Middleware {
return filterMethod("GET", hf)
}
// Put method filter
func Put(hf http.HandlerFunc) Middleware {
return filterMethod("PUT", hf)
}
// Delete method filter
func Delete(hf http.HandlerFunc) Middleware {
return filterMethod("DELETE", hf)
}
func filterMethod(method string, hf http.HandlerFunc) Middleware {
return func(next http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
if strings.ToUpper(req.Method) == method {
hf(rw, req)
}
next(rw, req)
}
}
}