This repository has been archived by the owner on Nov 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.go
98 lines (87 loc) · 2.37 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
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
package log
import (
"context"
"fmt"
"net/http"
"github.com/felixge/httpsnoop"
"github.com/livebud/middleware"
"github.com/segmentio/ksuid"
)
// ErrNotInContext is returned when a log is not in the context
var ErrNotInContext = fmt.Errorf("log: not in context")
type contextKey string
const logKey contextKey = "log"
// From gets the log from the context. If the logger isn't in the middleware,
// we warn and discards the logs
func From(ctx context.Context) (Log, error) {
log, ok := ctx.Value(logKey).(Log)
if !ok {
return nil, ErrNotInContext
}
return log, nil
}
// MustFrom gets the log from the context or panics
func MustFrom(ctx context.Context) Log {
log, err := From(ctx)
if err != nil {
panic(err)
}
return log
}
// WithRequestId sets the request id function for generating a unique request id
// for each request
func WithRequestId(fn func(r *http.Request) string) func(*middlewareOption) {
return func(opts *middlewareOption) {
opts.requestId = fn
}
}
type middlewareOption struct {
requestId func(r *http.Request) string
}
// RequestId is a function for generating a unique request id
func defaultRequestId(r *http.Request) string {
// Support an existing request id
requestId := r.Header.Get("X-Request-Id")
if requestId == "" {
requestId = ksuid.New().String()
// Set just in case we use it later
r.Header.Set("X-Request-Id", requestId)
}
return requestId
}
// Middleware uses the logger to log requests and responses
func Middleware(log Log, options ...func(*middlewareOption)) middleware.Middleware {
opts := &middlewareOption{
requestId: defaultRequestId,
}
for _, option := range options {
option(opts)
}
return middleware.Func(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log := log.Fields(Fields{
"url": r.RequestURI,
"method": r.Method,
"remote_addr": r.RemoteAddr,
"request_id": opts.requestId(r),
})
ctx := context.WithValue(r.Context(), logKey, log)
r = r.WithContext(ctx)
log.Info("request")
res := httpsnoop.CaptureMetrics(next, w, r)
log = log.Fields(Fields{
"status": res.Code,
"duration": res.Duration.Milliseconds(),
"size": res.Written,
})
switch {
case res.Code >= 500:
log.Error("response")
case res.Code >= 400:
log.Warn("response")
default:
log.Info("response")
}
})
})
}