this repo has no description
1package middleware
2
3import (
4 "log/slog"
5 "net/http"
6 "time"
7
8 "tangled.org/core/log"
9)
10
11func RequestLogger(next http.Handler) http.Handler {
12 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
13 ctx := r.Context()
14 l := log.FromContext(ctx)
15
16 start := time.Now()
17
18 next.ServeHTTP(w, r)
19
20 // Build query params as slog.Attrs for the group
21 queryParams := r.URL.Query()
22 queryAttrs := make([]any, 0, len(queryParams))
23 for key, values := range queryParams {
24 if len(values) == 1 {
25 queryAttrs = append(queryAttrs, slog.String(key, values[0]))
26 } else {
27 queryAttrs = append(queryAttrs, slog.Any(key, values))
28 }
29 }
30
31 l.LogAttrs(ctx, slog.LevelInfo, "",
32 slog.Group("request",
33 slog.String("method", r.Method),
34 slog.String("path", r.URL.Path),
35 slog.Group("query", queryAttrs...),
36 slog.Duration("duration", time.Since(start)),
37 ),
38 )
39 })
40}