-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathmiddleware.go
More file actions
85 lines (67 loc) · 2.74 KB
/
middleware.go
File metadata and controls
85 lines (67 loc) · 2.74 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
package httpserver
import (
"net/http"
"net/http/httputil"
"time"
libhttputil "github.com/Vonage/gosrvlib/pkg/httputil"
"github.com/Vonage/gosrvlib/pkg/logging"
"github.com/Vonage/gosrvlib/pkg/traceid"
"github.com/Vonage/gosrvlib/pkg/uidc"
"go.uber.org/zap"
)
// MiddlewareArgs contains extra optional arguments to be passed to the middleware handler function MiddlewareFn.
type MiddlewareArgs struct {
// Method is the HTTP method (e.g.: GET, POST, PUT, DELETE, ...).
Method string
// Path is the URL path.
Path string
// Description is the description of the route or a general description for the handler.
Description string
// TraceIDHeaderName is the Trace ID header name.
TraceIDHeaderName string
// RedactFunc is the function used to redact HTTP request and response dumps in the logs.
RedactFunc RedactFn
// Logger is the logger.
Logger *zap.Logger
}
// MiddlewareFn is a function that wraps an http.Handler.
type MiddlewareFn func(args MiddlewareArgs, next http.Handler) http.Handler
// RequestInjectHandler wraps all incoming requests and injects a logger in the request scoped context.
func RequestInjectHandler(logger *zap.Logger, traceIDHeaderName string, redactFn RedactFn, next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
reqTime := time.Now().UTC()
reqID := traceid.FromHTTPRequestHeader(r, traceIDHeaderName, uidc.NewID128())
l := logger.With(
zap.String(traceid.DefaultLogKey, reqID),
zap.Time("request_time", reqTime),
zap.String("request_method", r.Method),
zap.String("request_path", r.URL.Path),
zap.String("request_query", r.URL.RawQuery),
zap.String("request_remote_address", r.RemoteAddr),
zap.String("request_uri", r.RequestURI),
zap.String("request_user_agent", r.UserAgent()),
zap.String("request_x_forwarded_for", r.Header.Get("X-Forwarded-For")),
)
if l.Check(zap.DebugLevel, "debug") != nil {
reqDump, _ := httputil.DumpRequest(r, true)
l = l.With(zap.String("request", redactFn(string(reqDump))))
}
ctx := r.Context()
ctx = libhttputil.WithRequestTime(ctx, reqTime)
ctx = traceid.NewContext(ctx, reqID)
ctx = logging.WithLogger(ctx, l)
next.ServeHTTP(w, r.WithContext(ctx))
}
return http.HandlerFunc(fn)
}
// LoggerMiddlewareFn returns the middleware handler function to handle logs.
func LoggerMiddlewareFn(args MiddlewareArgs, next http.Handler) http.Handler {
return RequestInjectHandler(args.Logger, args.TraceIDHeaderName, args.RedactFunc, next)
}
// ApplyMiddleware returns an http Handler with all middleware handler functions applied.
func ApplyMiddleware(arg MiddlewareArgs, next http.Handler, middleware ...MiddlewareFn) http.Handler {
for i := len(middleware) - 1; i >= 0; i-- {
next = middleware[i](arg, next)
}
return next
}