-
Notifications
You must be signed in to change notification settings - Fork 162
/
http_rl_client.go
59 lines (53 loc) · 1.27 KB
/
http_rl_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
package main
import (
"context"
"fmt"
"net/http"
"time"
"golang.org/x/time/rate"
)
//RLHTTPClient Rate Limited HTTP Client
type RLHTTPClient struct {
client *http.Client
Ratelimiter *rate.Limiter
}
//Do dispatches the HTTP request to the network
func (c *RLHTTPClient) Do(req *http.Request) (*http.Response, error) {
// Comment out the below 5 lines to turn off ratelimiting
ctx := context.Background()
err := c.Ratelimiter.Wait(ctx) // This is a blocking call. Honors the rate limit
if err != nil {
return nil, err
}
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
//NewClient return http client with a ratelimiter
func NewClient(rl *rate.Limiter) *RLHTTPClient {
c := &RLHTTPClient{
client: http.DefaultClient,
Ratelimiter: rl,
}
return c
}
func main() {
rl := rate.NewLimiter(rate.Every(10*time.Second), 50) // 50 request every 10 seconds
c := NewClient(rl)
reqURL := "https://api.btcmarkets.net/v3/markets/BTC-AUD/ticker"
req, _ := http.NewRequest("GET", reqURL, nil)
for i := 0; i < 300; i++ {
resp, err := c.Do(req)
if err != nil {
fmt.Println(err.Error())
fmt.Println(resp.StatusCode)
return
}
if resp.StatusCode == 429 {
fmt.Printf("Rate limit reached after %d requests", i)
return
}
}
}