forked from HereMobilityDevelopers/mediary
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mediary.go
39 lines (33 loc) · 1.09 KB
/
mediary.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
package mediary
import (
"net/http"
)
type customRoundTripper struct {
inner http.RoundTripper
unitedInterceptor Interceptor
}
func prepareCustomRoundTripper(actual http.RoundTripper, interceptors ...Interceptor) http.RoundTripper {
return &customRoundTripper{
inner: actual,
unitedInterceptor: uniteInterceptors(interceptors),
}
}
func (crt *customRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
return crt.unitedInterceptor(req, crt.inner.RoundTrip)
}
func uniteInterceptors(interceptors []Interceptor) Interceptor {
if len(interceptors) == 0 {
return func(req *http.Request, handler Handler) (*http.Response, error) {
// That's why we needed an alias to http.RoundTripper.RoundTrip
return handler(req)
}
}
return func(req *http.Request, handler Handler) (*http.Response, error) {
tailhandler := func(innerReq *http.Request) (*http.Response, error) {
unitedInterceptor := uniteInterceptors(interceptors[1:])
return unitedInterceptor(req, handler)
}
headInterceptor := interceptors[0]
return headInterceptor(req, tailhandler)
}
}