-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogHandler.go
76 lines (73 loc) · 1.92 KB
/
logHandler.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package main
import (
"bytes"
"github.com/felixge/httpsnoop"
"github.com/google/uuid"
"io"
"log"
"net/http"
"net/http/httputil"
)
func LogAccess(logAccessFlag bool, prefix string, h http.Handler) http.Handler {
if !logAccessFlag {
return h
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var (
httpCode = http.StatusOK
writtenBytes int64 = 0
hooks = httpsnoop.Hooks{
WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
return func(code int) {
httpCode = code
next(code)
}
},
Write: func(next httpsnoop.WriteFunc) httpsnoop.WriteFunc {
return func(p []byte) (int, error) {
n, err := next(p)
writtenBytes += int64(n)
return n, err
}
},
ReadFrom: func(fromFunc httpsnoop.ReadFromFunc) httpsnoop.ReadFromFunc {
return func(src io.Reader) (int64, error) {
n, err := fromFunc(src)
writtenBytes += n
return n, err
}
},
}
)
wrapped := httpsnoop.Wrap(w, hooks)
h.ServeHTTP(wrapped, r)
log.Printf("%s %d %d %s", r.RemoteAddr, httpCode, writtenBytes, prefix + r.URL.Path)
})
}
func LogReqResponse(logReqResponse bool, postfix string, h http.Handler) http.Handler {
if !logReqResponse {
return h
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqUuid, _ := uuid.NewRandom()
reqId := reqUuid.String()[:8] + postfix
var (
respCode = http.StatusOK
hooks = httpsnoop.Hooks{
WriteHeader: func(next httpsnoop.WriteHeaderFunc) httpsnoop.WriteHeaderFunc {
return func(code int) {
respCode = code
next(code)
}
},
}
)
wrapped := httpsnoop.Wrap(w, hooks)
reqHeaders, _ := httputil.DumpRequest(r, false)
log.Printf(">>> %s %s", reqId, reqHeaders)
h.ServeHTTP(wrapped, r)
var b bytes.Buffer
_ = wrapped.Header().WriteSubset(&b, map[string]bool{})
log.Printf("<<< %s %d %s\n", reqId, respCode, b.String())
})
}