-
Notifications
You must be signed in to change notification settings - Fork 56
/
resty.go
119 lines (97 loc) · 2.55 KB
/
resty.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package helpers
import (
"bytes"
"crypto/tls"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/go-resty/resty/v2"
)
type actualRestyResponse struct {
*resty.Response
}
func NewActualRestyResponse(response *resty.Response) actualRestyResponse {
return actualRestyResponse{Response: response}
}
func (m actualRestyResponse) GomegaString() string {
return fmt.Sprintf(`
Request: %s %s
Request headers:
%s
Request body:
%+v
HTTP Status code: %d
Response headers:
%s
Response body:
%s`,
m.Request.Method, m.Request.URL,
headersString(m.Request.Header),
objectToPrettyJson(m.Request.Body),
m.StatusCode(),
headersString(m.Header()),
formatAsPrettyJson(m.Body()),
)
}
func headersString(headers http.Header) string {
var s []string
for k := range headers {
s = append(s, formatHeader(k, headers.Get(k)))
}
return strings.Join(s, "\n ")
}
func formatHeader(key, value string) string {
if key == "Authorization" {
return fmt.Sprintf("%s: %s", key, formatAuthorizationValue(value))
}
return fmt.Sprintf("%s: %s", key, value)
}
func formatAuthorizationValue(value string) string {
substrings := strings.Split(value, " ")
if len(substrings) != 2 {
return value
}
return fmt.Sprintf("%s %s", substrings[0], "<Redacted>")
}
func objectToPrettyJson(obj interface{}) string {
prettyJson, err := json.MarshalIndent(obj, " ", " ")
if err != nil {
return fmt.Sprintf("%+v", obj)
}
return string(prettyJson)
}
func formatAsPrettyJson(b []byte) string {
var prettyBuf bytes.Buffer
if err := json.Indent(&prettyBuf, b, " ", " "); err != nil {
return string(b)
}
return prettyBuf.String()
}
type CorrelatedRestyClient struct {
*resty.Client
getCorrelationId func() string
}
func NewCorrelatedRestyClient(apiServerRoot string, getCorrelationId func() string) *CorrelatedRestyClient {
return &CorrelatedRestyClient{
Client: resty.New().SetBaseURL(apiServerRoot),
getCorrelationId: getCorrelationId,
}
}
func (c *CorrelatedRestyClient) R() *resty.Request {
request := c.Client.R()
request.SetHeader("X-Correlation-ID", c.getCorrelationId())
return request
}
func (c *CorrelatedRestyClient) SetAuthToken(token string) *CorrelatedRestyClient {
c.Client.SetAuthToken(token)
return c
}
func (c *CorrelatedRestyClient) SetTLSClientConfig(config *tls.Config) *CorrelatedRestyClient {
c.Client.SetTLSClientConfig(config)
return c
}
func (c *CorrelatedRestyClient) SetAuthScheme(scheme string) *CorrelatedRestyClient {
c.Client.SetAuthScheme(scheme)
return c
}