-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.go
55 lines (45 loc) · 1.24 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
package httpgo
import (
"bytes"
"io"
"log"
"net/http"
)
type TransportFunc func(*http.Request) (*http.Response, error)
func (tf TransportFunc) RoundTrip(r *http.Request) (*http.Response, error) {
return tf(r)
}
type MiddlewareFunc func(http.RoundTripper) http.RoundTripper
func Middleware(t http.RoundTripper, mfs ...MiddlewareFunc) http.RoundTripper {
rt := t
for _, mf := range mfs {
rt = mf(rt)
}
return rt
}
func WithLogger(l *log.Logger) MiddlewareFunc {
return func(rt http.RoundTripper) http.RoundTripper {
return TransportFunc(func(req *http.Request) (*http.Response, error) {
buf := new(bytes.Buffer)
io.Copy(buf, req.Body)
req.Body = io.NopCloser(buf)
l.Printf("method: %v, requests: %v", req.URL.Path, buf.String())
resp, err := rt.RoundTrip(req)
buf.Reset()
if err == nil {
io.Copy(buf, resp.Body)
resp.Body = io.NopCloser(buf)
}
l.Printf("method: %v, response: %v", req.URL.Path, buf.String())
return resp, err
})
}
}
func WithBasicAuth(username, password string) MiddlewareFunc {
return func(rt http.RoundTripper) http.RoundTripper {
return TransportFunc(func(req *http.Request) (*http.Response, error) {
req.SetBasicAuth(username, password)
return rt.RoundTrip(req)
})
}
}