This repository has been archived by the owner on May 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
115 lines (94 loc) · 2.43 KB
/
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package rapidapi
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"time"
)
// API interface for a RapiAPI client
//go:generate mockery --name API
type API interface {
Call(endpoint string) (body []byte, err error)
CallWithContext(ctx context.Context, endpoint string) (body []byte, err error)
}
// Client represents a RapidAPI client
//
// For unit tests, set the URL field. This will ignore the hostname field.
type Client struct {
URL string
hostname string
apiKey string
httpClient *http.Client
}
// New creates a new client
func New(hostname, apiKey string) *Client {
return &Client{
httpClient: http.DefaultClient,
hostname: hostname,
apiKey: apiKey,
}
}
// WithHTTPClient sets the client's httpClient
func (client *Client) WithHTTPClient(httpClient *http.Client) *Client {
client.httpClient = httpClient
return client
}
// Call an endpoint on the API
func (client *Client) Call(endpoint string) (body []byte, err error) {
return client.CallWithContext(context.Background(), endpoint)
}
func (client Client) makeURL(endpoint string) string {
baseURL := "https://" + client.hostname
if client.URL != "" {
baseURL = client.URL
}
return baseURL + endpoint
}
// CallWithContext calls an endpoint on the API with a provided context
func (client *Client) CallWithContext(ctx context.Context, endpoint string) (body []byte, err error) {
url := client.makeURL(endpoint)
const (
initWaitTime = 100 * time.Millisecond
maxWaitTime = 5 * time.Second
maxRetry = 10
)
waitTime := initWaitTime
for retries := 0; retries < maxRetry; retries++ {
body, err = client.call(ctx, url)
if err == nil {
break
}
if err.Error() != fmt.Sprintf("%3d %s", http.StatusTooManyRequests, http.StatusText(http.StatusTooManyRequests)) {
break
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(waitTime):
break
}
if waitTime < maxWaitTime {
waitTime *= 2
}
}
return
}
func (client *Client) call(ctx context.Context, url string) (body []byte, err error) {
req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
req.Header.Add("x-rapidapi-key", client.apiKey)
req.Header.Add("x-rapidapi-host", client.hostname)
var resp *http.Response
resp, err = client.httpClient.Do(req)
if err != nil {
return
}
defer func() {
_ = resp.Body.Close()
}()
if resp.StatusCode != http.StatusOK {
return nil, errors.New(resp.Status)
}
return io.ReadAll(resp.Body)
}