-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
formatter_http.go
72 lines (63 loc) · 1.88 KB
/
formatter_http.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
package slogformatter
import (
"net/http"
"strings"
"log/slog"
"github.com/samber/lo"
)
// HTTPRequestFormatter transforms a *http.Request into a readable object.
func HTTPRequestFormatter(ignoreHeaders bool) Formatter {
headers := slog.String("headers", "[hidden]")
return FormatByType(func(req *http.Request) slog.Value {
if !ignoreHeaders {
headers = slog.Group(
"headers",
lo.ToAnySlice(lo.MapToSlice(req.Header, func(key string, values []string) slog.Attr {
return slog.String(key, strings.Join(values, ","))
}))...,
)
}
return slog.GroupValue(
slog.String("host", req.Host),
slog.String("method", req.Method),
slog.String("url", req.URL.String()),
slog.Group(
"url",
slog.String("url", req.URL.String()),
slog.String("scheme", req.URL.Scheme),
slog.String("host", req.URL.Host),
slog.String("path", req.URL.Path),
slog.String("raw_query", req.URL.RawQuery),
slog.String("fragment", req.URL.Fragment),
slog.Group(
"query",
lo.ToAnySlice(lo.MapToSlice(req.URL.Query(), func(key string, values []string) slog.Attr {
return slog.String(key, strings.Join(values, ","))
}))...,
),
),
headers,
)
})
}
// HTTPResponseFormatter transforms a *http.Response into a readable object.
func HTTPResponseFormatter(ignoreHeaders bool) Formatter {
headers := slog.String("headers", "[hidden]")
return FormatByType(func(res *http.Response) slog.Value {
if !ignoreHeaders {
headers = slog.Group(
"headers",
lo.ToAnySlice(lo.MapToSlice(res.Header, func(key string, values []string) slog.Attr {
return slog.String(key, strings.Join(values, ","))
}))...,
)
}
return slog.GroupValue(
slog.Int("status", res.StatusCode),
slog.String("status_text", res.Status),
slog.Int64("content_length", res.ContentLength),
slog.Bool("uncompressed", res.Uncompressed),
headers,
)
})
}