-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmiddleware.go
More file actions
101 lines (79 loc) · 2.88 KB
/
middleware.go
File metadata and controls
101 lines (79 loc) · 2.88 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
package httpserver
import (
"log/slog"
"net/http"
"net/http/httputil"
"time"
libhttputil "github.com/tecnickcom/gogen/pkg/httputil"
"github.com/tecnickcom/gogen/pkg/random"
"github.com/tecnickcom/gogen/pkg/traceid"
)
// 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 *slog.Logger
// Rnd is the random generator.
Rnd *random.Rnd
}
// 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 *slog.Logger,
traceIDHeaderName string,
redactFn RedactFn,
rnd *random.Rnd,
next http.Handler,
) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
reqTime := time.Now().UTC()
reqID := traceid.FromHTTPRequestHeader(r, traceIDHeaderName, rnd.UUIDv7().String())
ctx := r.Context()
ctx = libhttputil.WithRequestTime(ctx, reqTime)
ctx = traceid.NewContext(ctx, reqID)
logger = logger.With(
slog.String(traceid.DefaultLogKey, reqID),
slog.Time("request_time", reqTime),
slog.String("request_method", r.Method),
slog.String("request_path", r.URL.Path),
slog.String("request_query", r.URL.RawQuery),
slog.String("request_remote_address", r.RemoteAddr),
slog.String("request_uri", r.RequestURI),
slog.String("request_user_agent", r.UserAgent()),
slog.String("request_x_forwarded_for", r.Header.Get("X-Forwarded-For")),
)
dbglog := logger.Enabled(ctx, slog.LevelDebug)
if dbglog {
reqDump, _ := httputil.DumpRequest(r, true)
logger = logger.With(slog.String("request_dump", redactFn(string(reqDump))))
}
next.ServeHTTP(w, r.WithContext(ctx))
if dbglog {
logger.Debug("request")
return
}
logger.Info("request")
}
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, args.Rnd, 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
}