forked from open-horizon/edge-sync-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpWrapper.go
44 lines (35 loc) · 1022 Bytes
/
httpWrapper.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
package communications
import (
"context"
"net/http"
"sync"
)
type httpRequestWrapper struct {
httpClient http.Client
inFlight map[*http.Request]context.CancelFunc
lock sync.Mutex
}
func newHTTPRequestWrapper(httpClient http.Client) *httpRequestWrapper {
wrapper := httpRequestWrapper{httpClient: httpClient, inFlight: make(map[*http.Request]context.CancelFunc)}
return &wrapper
}
func (wrapper *httpRequestWrapper) do(request *http.Request) (*http.Response, error) {
ctx, cancel := context.WithCancel(context.Background())
reqWithCtx := request.WithContext(ctx)
wrapper.lock.Lock()
wrapper.inFlight[reqWithCtx] = cancel
wrapper.lock.Unlock()
response, err := wrapper.httpClient.Do(reqWithCtx)
wrapper.lock.Lock()
delete(wrapper.inFlight, reqWithCtx)
wrapper.lock.Unlock()
return response, err
}
func (wrapper *httpRequestWrapper) cancel() {
wrapper.lock.Lock()
for request, cancel := range wrapper.inFlight {
cancel()
delete(wrapper.inFlight, request)
}
wrapper.lock.Unlock()
}