/
client_opts.go
65 lines (51 loc) · 1.36 KB
/
client_opts.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
package mittwaldv2
import (
"bytes"
"github.com/hashicorp/terraform-plugin-log/tflog"
"io"
"net/http"
)
type ClientBuilderOption func(*clientBuilder, *Client)
func WithAPIToken(token string) ClientBuilderOption {
return func(_ *clientBuilder, c *Client) {
c.RequestEditors = append(c.RequestEditors, apiTokenRequestEditor(token))
}
}
func WithEndpoint(endpoint string) ClientBuilderOption {
return func(_ *clientBuilder, c *Client) {
c.Server = endpoint
}
}
type debuggingClient struct {
HttpRequestDoer
withRequestBodies bool
}
func (c *debuggingClient) Do(req *http.Request) (*http.Response, error) {
logFields := map[string]any{
"method": req.Method,
"url": req.URL.String(),
}
if req.Body != nil && c.withRequestBodies {
body, err := io.ReadAll(req.Body)
if err != nil {
return nil, err
}
req.Body = io.NopCloser(bytes.NewBuffer(body))
logFields["body"] = string(body)
}
res, err := c.HttpRequestDoer.Do(req)
if res != nil {
logFields["status"] = res.StatusCode
}
if err != nil {
logFields["err"] = err
}
tflog.Debug(req.Context(), "executed request", logFields)
return res, err
}
func WithDebugging(withRequestBodies bool) ClientBuilderOption {
return func(_ *clientBuilder, c *Client) {
originalClient := c.Client
c.Client = &debuggingClient{HttpRequestDoer: originalClient, withRequestBodies: withRequestBodies}
}
}