forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adjustable_client.go
53 lines (40 loc) · 1.02 KB
/
adjustable_client.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
package director
import (
"net/http"
)
//go:generate counterfeiter . Adjustment
type Adjustment interface {
Adjust(req *http.Request, retried bool) error
NeedsReadjustment(*http.Response) bool
}
//go:generate counterfeiter . AdjustedClient
type AdjustedClient interface {
Do(*http.Request) (*http.Response, error)
}
type AdjustableClient struct {
client AdjustedClient
adjustment Adjustment
}
func NewAdjustableClient(client AdjustedClient, adjustment Adjustment) AdjustableClient {
return AdjustableClient{client: client, adjustment: adjustment}
}
func (c AdjustableClient) Do(req *http.Request) (*http.Response, error) {
retried := req.Body != nil
err := c.adjustment.Adjust(req, retried)
if err != nil {
return nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return resp, err
}
if c.adjustment.NeedsReadjustment(resp) {
err := c.adjustment.Adjust(req, true)
if err != nil {
return nil, err
}
// Try one more time again after an adjustment
return c.client.Do(req)
}
return resp, nil
}