-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinterceptor.go
44 lines (31 loc) · 1.26 KB
/
interceptor.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
package hx
import "net/http"
func Intercept(i Interceptor) Option {
return OptionFunc(func(c *Config) error { c.Interceptors = append(c.Interceptors, i); return nil })
}
func InterceptFunc(f func(*http.Client, *http.Request, RequestFunc) (*http.Response, error)) Option {
return Intercept(InterceptorFunc(f))
}
type RequestFunc = func(*http.Client, *http.Request) (*http.Response, error)
type Interceptor interface {
DoRequest(*http.Client, *http.Request, RequestFunc) (*http.Response, error)
Wrap(RequestFunc) RequestFunc
}
var _ Interceptor = InterceptorFunc(nil)
type InterceptorFunc func(*http.Client, *http.Request, RequestFunc) (*http.Response, error)
func (i InterceptorFunc) DoRequest(c *http.Client, r *http.Request, next RequestFunc) (*http.Response, error) {
return i(c, r, next)
}
func (i InterceptorFunc) Wrap(f RequestFunc) RequestFunc {
return func(c *http.Client, r *http.Request) (*http.Response, error) { return i.DoRequest(c, r, f) }
}
func combineInterceptors(interceptors []Interceptor) Interceptor {
n := len(interceptors)
return InterceptorFunc(func(cli *http.Client, req *http.Request, f RequestFunc) (*http.Response, error) {
next := f
for i := n - 1; i >= 0; i-- {
next = interceptors[i].Wrap(next)
}
return next(cli, req)
})
}