-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.go
51 lines (43 loc) · 1.05 KB
/
request.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
package middleware
import (
"bytes"
"io/ioutil"
"net/http"
)
type HTTPRequestLog struct {
Method string
Path string
UserAgent string
RemoteAddress string
Payload string
Header http.Header
}
func (m *Middleware) LoggerRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer next.ServeHTTP(w, r)
buf := new(bytes.Buffer)
if r.Body != nil {
bodyBuf, err := ioutil.ReadAll(r.Body)
if err != nil {
m.log.Errorf("error read body: %s\n", err)
return
}
temp1 := ioutil.NopCloser(bytes.NewBuffer(bodyBuf))
temp2 := ioutil.NopCloser(bytes.NewBuffer(bodyBuf))
_, err = buf.ReadFrom(temp1)
if err != nil {
m.log.Errorf("error read buffer: %s\n", err)
return
}
r.Body = temp2
}
m.log.Infof("Request: %+v\n", &HTTPRequestLog{
Method: r.Method,
Path: r.URL.Path,
UserAgent: r.UserAgent(),
RemoteAddress: r.RemoteAddr,
Payload: buf.String(),
Header: r.Header,
})
})
}