-
Notifications
You must be signed in to change notification settings - Fork 0
/
semaphore_client.go
64 lines (52 loc) · 1.22 KB
/
semaphore_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
54
55
56
57
58
59
60
61
62
63
64
package gosrm
import "net/http"
type (
// httpClient is the default implementation of HTTPClient interface.
httpClient struct {
client *http.Client
pool chan struct{}
}
// HTTPClientConfig is the config used to customize http client.
HTTPClientConfig struct {
// MaxConcurrency is the max number of concurrent requests.
// If it's 0 then there is no limit.
//
// Defaults to 0.
MaxConcurrency uint
// HTTPClient is the client which will be used to do HTTP calls.
//
// Defaults to http.DefaultClient
HTTPClient *http.Client
}
)
// acquire acquires a spot in the pool.
func (c httpClient) acquire() {
if cap(c.pool) == 0 {
return
}
c.pool <- struct{}{}
}
// release releases a spot from the pool.
func (c httpClient) release() {
if cap(c.pool) == 0 {
return
}
<-c.pool
}
// Do does the HTTP call.
func (c httpClient) Do(req *http.Request) (*http.Response, error) {
c.acquire()
defer c.release()
return c.client.Do(req)
}
// NewHTTPClient returns a new HTTP client.
func NewHTTPClient(cfg HTTPClientConfig) HTTPClient {
var c httpClient
if cfg.HTTPClient != nil {
c.client = cfg.HTTPClient
} else {
c.client = http.DefaultClient
}
c.pool = make(chan struct{}, cfg.MaxConcurrency)
return c
}