-
Notifications
You must be signed in to change notification settings - Fork 111
/
helpers.go
87 lines (72 loc) · 2.18 KB
/
helpers.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
package integration
import (
"encoding/json"
"io/ioutil"
"net/http"
"time"
uuid "github.com/chef/automate/lib/uuid4"
"github.com/pkg/errors"
)
// TimestampName returns a name with a timestamp
func TimestampName() string {
ts := time.Now()
return "diagnostic-" + ts.Format("20060102150405")
}
// Password returns a random password
func Password() string {
return uuid.Must(uuid.NewV4()).String()
}
// mustJSONDecodeSuccess is a thing that will hold a http response or error. It
// should wrap a result that must be 200 to be considered successful
type mustJSONDecodeSuccess struct {
resp *http.Response
err error
}
// MustJSONDecodeSuccess wraps an http request response and error that must not error
// and must 200. You can also decode the json value with it, and it must succeed
func MustJSONDecodeSuccess(resp *http.Response, err error) *mustJSONDecodeSuccess {
return &mustJSONDecodeSuccess{
resp: resp,
err: err,
}
}
// WithValue deserializes the json body of the response into value if a 200 is returned.
// Otherwise, an error is returned.
func (m *mustJSONDecodeSuccess) WithValue(value interface{}) error {
if m.err != nil {
return m.err
}
reqPath := m.resp.Request.URL.String()
method := m.resp.Request.Method
defer func() {
_ = m.resp.Body.Close()
}()
body, err := ioutil.ReadAll(m.resp.Body)
if err != nil {
return errors.Wrapf(err, "Failed to %s %s. Could not read body", method, reqPath)
}
if m.resp.StatusCode != 200 {
return errors.Errorf("Failed to %s %s. Received unexpected status code %d\nResponse Body:\n %s", method, reqPath, m.resp.StatusCode, body)
}
err = json.Unmarshal(body, value)
if err != nil {
return errors.Wrapf(err, "Failed to %s %s. Could not decode body.\nResponse Body:\n %s", method, reqPath, body)
}
return nil
}
// Error returns an error if this represents an error, otherwise nil
func (m *mustJSONDecodeSuccess) Error() error {
return m.err
}
// Retry calls f. If f returns an error, it will be retried again after the
// backoff and at most times times.
func Retry(times int, backoff time.Duration, f func() error) error {
for {
err := f()
times--
if err == nil || times <= 0 {
return err
}
time.Sleep(backoff)
}
}