-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpclient.go
97 lines (71 loc) · 2.14 KB
/
httpclient.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
package liberlogger
import (
"bytes"
"context"
"io"
"net/http"
)
// This type implements the http.RoundTripper interface
type HttpClient struct {
Proxied http.RoundTripper
RedactedKeys []string
Maskedkeys []string
}
func (hc HttpClient) getRequestBody(req *http.Request) any {
var bodyRequest map[string]any
err := extractBody(req, &bodyRequest)
if err != nil {
bodyBytes, _ := io.ReadAll(req.Body)
defer req.Body.Close()
req.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
return string(bodyBytes)
}
return Redact(hc.RedactedKeys, hc.Maskedkeys, bodyRequest)
}
func (hc HttpClient) getResponseBody(res *http.Response) any {
var bodyResponse map[string]any
err := extractBody(res, &bodyResponse)
if err != nil {
bodyBytes, _ := io.ReadAll(res.Body)
defer res.Body.Close()
res.Body = io.NopCloser(bytes.NewBuffer(bodyBytes))
return string(bodyBytes)
}
return Redact(hc.RedactedKeys, hc.Maskedkeys, bodyResponse)
}
func (hc HttpClient) RoundTrip(req *http.Request) (res *http.Response, err error) {
ctx := context.TODO()
requestBody := hc.getRequestBody(req)
Info(ctx).
Interface("headers", Redact(hc.RedactedKeys, hc.Maskedkeys, parseHeaders(req.Header))).
Interface("body", requestBody).
Dict("extra", extraLogs(req, nil)).
Msg(formatFinalMsg(req, "HTTP Client"))
res, err = hc.Proxied.RoundTrip(req)
if err != nil {
Error(ctx, err).
Interface("headers", Redact(hc.RedactedKeys, hc.Maskedkeys, parseHeaders(req.Header))).
Dict("extra", extraLogs(req, err)).
Msg(formatFinalMsg(req, "HTTP Client"))
return
}
responseBody := hc.getResponseBody(res)
Info(ctx).
Interface("headers", Redact(hc.RedactedKeys, hc.Maskedkeys, parseHeaders(res.Header))).
Interface("body", responseBody).
Dict("extra", extraLogs(res, nil)).
Msg(formatFinalMsg(res, "HTTP Client"))
return
}
func (hc *HttpClient) AddKeysToMask(keys []string) {
if hc.Maskedkeys != nil && keys != nil {
hc.Maskedkeys = append(hc.Maskedkeys, keys...)
return
}
}
func (hc *HttpClient) AddKeysToRedact(keys []string) {
if hc.RedactedKeys != nil && keys != nil {
hc.RedactedKeys = append(hc.RedactedKeys, keys...)
return
}
}