-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterceptor_http.go
40 lines (34 loc) · 1.27 KB
/
interceptor_http.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
package interceptor
import (
"net/http"
)
type HttpInterceptor func(http.ResponseWriter, *http.Request, http.HandlerFunc) http.HandlerFunc
func ChainHttpInterceptor(interceptors ...HttpInterceptor) HttpInterceptor {
n := len(interceptors)
return func(rw http.ResponseWriter, req *http.Request, handler http.HandlerFunc) http.HandlerFunc {
chainer := func(currInterceptor HttpInterceptor, currHandler http.HandlerFunc) http.HandlerFunc {
return currInterceptor(rw, req, currHandler)
}
currHandler := handler
for i := n - 1; i >= 0; i-- {
currHandler = chainer(interceptors[i], currHandler)
}
currHandler.ServeHTTP(rw, req)
// currHandler(rw, req)
return currHandler
}
}
func HttpInterceptorWarp(interceptors ...HttpInterceptor) func(http.HandlerFunc) http.HandlerFunc {
chainInterceptor := ChainHttpInterceptor(interceptors...)
return func(handler http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, req *http.Request) {
chainInterceptor(rw, req, handler)
}
}
}
func HttpInterceptorWarpHandleFunc(handler http.HandlerFunc, interceptors ...HttpInterceptor) http.HandlerFunc {
chainInterceptor := ChainHttpInterceptor(interceptors...)
return func(rw http.ResponseWriter, req *http.Request) {
chainInterceptor(rw, req, handler)
}
}