-
Notifications
You must be signed in to change notification settings - Fork 0
/
middle.go
44 lines (35 loc) · 914 Bytes
/
middle.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 greq
import "net/http"
// Middleware interface for cli request.
type Middleware interface {
Handle(r *http.Request, next HandleFunc) (*Response, error)
}
// MiddleFunc implements the Middleware interface
type MiddleFunc func(r *http.Request, next HandleFunc) (*Response, error)
// Handle request
func (mf MiddleFunc) Handle(r *http.Request, next HandleFunc) (*Response, error) {
return mf(r, next)
}
func (h *Client) wrapMiddlewares() {
h.handler = func(r *http.Request) (*Response, error) {
rawResp, err := h.doer.Do(r)
if err != nil {
return nil, err
}
return &Response{
Response: rawResp,
// with decoder
decoder: h.respDecoder,
}, nil
}
for _, m := range h.middles {
h.wrapMiddleware(m)
}
}
func (h *Client) wrapMiddleware(m Middleware) {
next := h.handler
// wrap handler
h.handler = func(r *http.Request) (*Response, error) {
return m.Handle(r, next)
}
}