-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
251 lines (211 loc) · 5.76 KB
/
middleware.go
File metadata and controls
251 lines (211 loc) · 5.76 KB
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"runtime/debug"
"strings"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
type Middleware func(http.Handler) http.Handler
func chainMiddleware(h http.Handler, middlewares ...Middleware) http.Handler {
for _, middleware := range middlewares {
h = middleware(h)
}
return h
}
type responseWriter struct {
http.ResponseWriter
status int
wroteHeader bool
}
func wrapResponseWriter(w http.ResponseWriter) *responseWriter {
return &responseWriter{ResponseWriter: w}
}
func (rw *responseWriter) Status() int {
return rw.status
}
func (rw *responseWriter) WriteHeader(code int) {
if !rw.wroteHeader {
rw.status = code
rw.wroteHeader = true
rw.ResponseWriter.WriteHeader(code)
}
}
func logSeverity(statusCode int) zerolog.Level {
switch {
case statusCode >= 500:
return zerolog.ErrorLevel
case statusCode >= 400:
return zerolog.ErrorLevel
case statusCode >= 300:
return zerolog.WarnLevel
case statusCode >= 200:
return zerolog.InfoLevel
default:
return zerolog.DebugLevel
}
}
type logFields struct {
RemoteIP string
Host string
UserAgent string
Method string
Path string
Body string
StatusCode int
Latency float64
}
func (l *logFields) MarshalZerologObject(e *zerolog.Event) {
e.
Str("remote_ip", l.RemoteIP).
Str("host", l.Host).
Str("user_agent", l.UserAgent).
Str("method", l.Method).
Str("path", l.Path).
Str("body", l.Body).
Int("status_code", l.StatusCode).
Float64("latency", l.Latency)
}
func loggerHandler(filter func(w http.ResponseWriter, r *http.Request) bool) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Check filter
if filter != nil && filter(w, r) {
next.ServeHTTP(w, r)
return
}
// Start timer
start := time.Now()
// Read request body
var buf []byte
if r.Body != nil {
buf, _ = io.ReadAll(r.Body)
// Restore the io.ReadCloser to its original state
r.Body = io.NopCloser(bytes.NewBuffer(buf))
}
// Wraps an http.ResponseWriter, returning a proxy that allows you to
// hook into various parts of the response process.
ww := wrapResponseWriter(w)
next.ServeHTTP(ww, r)
dur := float64(time.Since(start).Nanoseconds()/1e4) / 100.0
// Create log fields
fields := &logFields{
RemoteIP: r.RemoteAddr,
Host: r.Host,
UserAgent: r.UserAgent(),
Method: r.Method,
Path: r.URL.Path,
Body: formatReqBody(r, buf),
StatusCode: ww.Status(),
Latency: dur,
}
sev := logSeverity(ww.Status())
logEntry := log.Ctx(r.Context()).WithLevel(sev).EmbedObject(fields)
logEntry.Msg("http request")
})
}
}
func formatReqBody(r *http.Request, data []byte) string {
var js map[string]any
if json.Unmarshal(data, &js) != nil {
return string(data)
}
result := new(bytes.Buffer)
if err := json.Compact(result, data); err != nil {
log.Ctx(r.Context()).Error().Msgf("error compacting body request json: %s", err.Error())
return ""
}
return result.String()
}
func realIPHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if rip := realIP(r); rip != "" {
r.RemoteAddr = rip
}
next.ServeHTTP(w, r)
})
}
func realIP(r *http.Request) string {
trueClientIP := http.CanonicalHeaderKey("True-Client-IP")
xForwardedFor := http.CanonicalHeaderKey("X-Forwarded-For")
xRealIP := http.CanonicalHeaderKey("X-Real-IP")
var ip string
if tcip := r.Header.Get(trueClientIP); tcip != "" {
ip = tcip
} else if xrip := r.Header.Get(xRealIP); xrip != "" {
ip = xrip
} else if xff := r.Header.Get(xForwardedFor); xff != "" {
i := strings.Index(xff, ",")
if i == -1 {
i = len(xff)
}
ip = xff[:i]
}
if ip == "" || net.ParseIP(ip) == nil {
return ""
}
return ip
}
func recoverHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if rvr := recover(); rvr != nil {
if rvr == http.ErrAbortHandler {
// we don't recover http.ErrAbortHandler so the response
// to the client is aborted, this should not be logged
panic(rvr)
}
err, ok := rvr.(error)
if !ok {
err = fmt.Errorf("%v", rvr)
}
log.Ctx(r.Context()).
Error().
Err(err).
Bytes("stack", debug.Stack()).
Msg("panic recover")
w.WriteHeader(http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
func requestIDHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestIDHeader := "X-Request-Id"
requestID := r.Header.Get(requestIDHeader)
if requestID == "" {
requestID = uuid.NewString()
r.Header.Set(requestIDHeader, requestID)
}
// Set request ID in response header
w.Header().Set(requestIDHeader, requestID)
ctx := log.With().
Str("request_id", requestID).
Logger().
WithContext(r.Context())
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
func corsHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, Qiscus-App-Id, Qiscus-Secret-Key")
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, HEAD, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Max-Age", "3600")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}