-
Notifications
You must be signed in to change notification settings - Fork 2
/
http_middleware.go
203 lines (173 loc) · 4.53 KB
/
http_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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package log
import (
"bytes"
"io"
"net"
"net/http"
"time"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/rl404/fairy/errors/stack"
)
// APIMiddlewareConfig is log config for middleware.
type APIMiddlewareConfig struct {
// Show request header.
RequestHeader bool
// Show request body.
RequestBody bool
// Show response header.
ResponseHeader bool
// Show response body.
ResponseBody bool
// Show raw path (includes query params).
RawPath bool
// Show error stack.
Error bool
}
// HTTPMiddlewareWithLog is http middleware that will log the request and response.
func HTTPMiddlewareWithLog(logger Logger, middlewareConfig ...APIMiddlewareConfig) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return HTTPHandlerWithLog(logger, next, middlewareConfig...)
}
}
// HTTPHandlerFuncWithLog is http handler func with log.
func HTTPHandlerFuncWithLog(logger Logger, next http.HandlerFunc, middlewareConfig ...APIMiddlewareConfig) http.HandlerFunc {
return HTTPHandlerWithLog(logger, next, middlewareConfig...).(http.HandlerFunc)
}
// HTTPHandlerWithLog is http handler with log.
// Also includes error stack tracing feature
// if you use it.
func HTTPHandlerWithLog(logger Logger, next http.Handler, middlewareConfig ...APIMiddlewareConfig) http.Handler {
var cfg APIMiddlewareConfig
if len(middlewareConfig) > 0 {
cfg = middlewareConfig[0]
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if logger == nil {
next.ServeHTTP(w, r)
return
}
// Prepare error stack tracing.
ctx := stack.Init(r.Context())
start := time.Now()
var bw bodyWriter
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
ww.Tee(&bw)
// Get request body.
var body []byte
if r.Body != nil {
b, err := io.ReadAll(r.Body)
if err != nil {
_ = stack.Wrap(ctx, err)
}
body, r.Body = b, io.NopCloser(bytes.NewBuffer(b))
}
// Call next handler.
next.ServeHTTP(ww, r.WithContext(ctx))
// Prepare map for logging.
m := map[string]interface{}{
"level": getLevelFromStatus(ww.Status()),
"duration": time.Since(start).String(),
"method": r.Method,
"path": r.URL.Path,
"code": ww.Status(),
"ip": getIP(r),
}
if path, ok := getRoutePattern(r); ok {
m["path"] = path
}
if cfg.RawPath {
m["raw_path"] = r.RequestURI
}
if cfg.RequestHeader {
m["request_header"] = r.Header
}
if cfg.RequestBody {
m["request_body"] = string(body)
}
if cfg.ResponseHeader {
m["response_header"] = ww.Header()
}
if cfg.ResponseBody {
m["response_body"] = string(bw.Body)
}
// Include the error stack if you use it.
errStack := stack.Get(ctx)
if cfg.Error && len(errStack) > 0 {
// Copy slice to prevent reversed multiple times
// if using multiple middleware.
errTmp := cpSlice(errStack)
// Reverse the stack order.
for i, j := 0, len(errTmp)-1; i < j; i, j = i+1, j-1 {
errTmp[i], errTmp[j] = errTmp[j], errTmp[i]
}
m["error"] = errTmp
}
logger.Log(m)
})
}
func cpSlice(arr []stack.ErrStack) []stack.ErrStack {
a := make([]stack.ErrStack, len(arr))
copy(a, arr)
return a
}
func getRoutePattern(r *http.Request) (string, bool) {
routePath := r.URL.Path
if r.URL.RawPath != "" {
routePath = r.URL.RawPath
}
rctx := chi.RouteContext(r.Context())
tctx := chi.NewRouteContext()
if rctx.Routes.Match(tctx, r.Method, routePath) {
return tctx.RoutePattern(), true
}
return "", false
}
func getLevelFromStatus(status int) logLevel {
switch status {
case
http.StatusOK,
http.StatusCreated,
http.StatusAccepted,
http.StatusMultipleChoices,
http.StatusMovedPermanently,
http.StatusFound,
http.StatusSeeOther,
http.StatusNotModified,
http.StatusTemporaryRedirect,
http.StatusPermanentRedirect:
return infoLevel
case
http.StatusBadRequest,
http.StatusUnauthorized,
http.StatusForbidden,
http.StatusNotFound,
http.StatusMethodNotAllowed,
http.StatusNotAcceptable,
http.StatusRequestTimeout,
http.StatusConflict,
http.StatusGone,
http.StatusPreconditionFailed,
http.StatusExpectationFailed,
http.StatusMisdirectedRequest,
http.StatusUnprocessableEntity,
http.StatusFailedDependency,
http.StatusTooManyRequests:
return warnLevel
default:
return errorLevel
}
}
func getIP(r *http.Request) string {
if host, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return host
}
return r.RemoteAddr
}
type bodyWriter struct {
Body []byte
}
func (w *bodyWriter) Write(b []byte) (int, error) {
w.Body = b
return len(b), nil
}