forked from vmware-archive/atc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
round_tripper.go
51 lines (41 loc) · 1.16 KB
/
round_tripper.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
package transport
import "net/http"
//go:generate counterfeiter . RoundTripper
type RoundTripper interface {
RoundTrip(*http.Request) (*http.Response, error)
}
type roundTripper struct {
db TransportDB
workerName string
innerRoundTripper http.RoundTripper
cachedHost string
}
func NewRoundTripper(workerName string, workerHost string, db TransportDB, innerRoundTripper http.RoundTripper) http.RoundTripper {
return &roundTripper{
innerRoundTripper: innerRoundTripper,
workerName: workerName,
db: db,
cachedHost: workerHost,
}
}
func (c *roundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
if c.cachedHost == "" {
savedWorker, found, err := c.db.GetWorker(c.workerName)
if err != nil {
return nil, err
}
if !found {
return nil, ErrMissingWorker{WorkerName: c.workerName}
}
c.cachedHost = savedWorker.GardenAddr
}
updatedURL := *request.URL
updatedURL.Host = c.cachedHost
updatedRequest := *request
updatedRequest.URL = &updatedURL
response, err := c.innerRoundTripper.RoundTrip(&updatedRequest)
if err != nil {
c.cachedHost = ""
}
return response, err
}