-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiclient.go
188 lines (174 loc) · 4.28 KB
/
apiclient.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
package apiclient
import (
//"bufio"
//"crypto/sha1"
//"encoding/hex"
"encoding/json"
//"fmt"
"io/ioutil"
"log"
"net/http"
"net/http/cookiejar"
//"net/http/httputil"
"net/url"
//"os"
"path/filepath"
"strings"
"time"
"golang.org/x/net/publicsuffix"
"github.com/pkg/errors"
"github.com/rclancey/cache"
"github.com/rclancey/cache/fs"
)
type APIClientOptions struct {
BaseURL string
RequestTimeout time.Duration
CacheStore cache.CacheStore
MaxCacheTime time.Duration
MaxRequestsPerSecond float64
Auth Authenticator
}
type HTTPClient struct {
client *http.Client
lastRequest time.Time
rateLimit float64
}
func NewHTTPClient(opts APIClientOptions) (*HTTPClient, error) {
if opts.RequestTimeout == 0 {
opts.RequestTimeout = 5 * time.Second
}
if opts.MaxRequestsPerSecond == 0 {
opts.MaxRequestsPerSecond = 10.0
}
jar, err := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
if err != nil {
return nil, errors.Wrap(err, "can't open cookie jar")
}
cli := &http.Client{Jar: jar, Timeout: opts.RequestTimeout}
return &HTTPClient{
client: cli,
lastRequest: time.Time{},
rateLimit: opts.MaxRequestsPerSecond,
}, nil
}
func (c *HTTPClient) Do(req *http.Request) (*http.Response, error) {
if c.rateLimit > 0 {
t := c.lastRequest.Add(time.Duration(float64(time.Second) / c.rateLimit))
delay := t.Sub(time.Now())
if delay > 0 {
log.Printf("ratelimiting %s", delay)
time.Sleep(delay)
}
}
log.Println(req.Method, req.URL)
return c.client.Do(req)
}
func (c *HTTPClient) Get(u string) (*http.Response, error) {
req, err := http.NewRequest(http.MethodGet, u, nil)
if err != nil {
return nil, err
}
return c.Do(req)
}
type APIClient struct {
BaseURL *url.URL
CacheDirectory string
MaxCacheTime time.Duration
MaxRequestsPerSecond float64
Authenticator Authenticator
cache *cache.Cache
client *HTTPClient
lastFetch time.Time
}
func NewAPIClient(opts APIClientOptions) (*APIClient, error) {
if opts.CacheStore == nil {
pth, err := filepath.Abs(filepath.Join(".", "var", "cache"))
if err != nil {
return nil, err
}
opts.CacheStore = fscache.NewFSCacheStore(pth)
}
if opts.MaxCacheTime == 0 {
opts.MaxCacheTime = 24 * time.Hour
}
u, err := url.Parse(opts.BaseURL)
if err != nil {
return nil, errors.Wrap(err, "can't parse base url " + opts.BaseURL)
}
cli, err := NewHTTPClient(opts)
if err != nil {
return nil, err
}
cacher := cache.NewCache(opts.CacheStore, cli)
c := &APIClient{
BaseURL: u,
MaxCacheTime: opts.MaxCacheTime,
Authenticator: opts.Auth,
cache: cacher,
client: cli,
lastFetch: time.Unix(0, 0),
}
return c, nil
}
func (c *APIClient) Client() *HTTPClient {
return c.client
}
func (c *APIClient) Do(req *http.Request) (*http.Response, error) {
res, err := c.cache.CacheRequest(req, c.MaxCacheTime)
if res != nil && err == nil {
return res, nil
}
/*
res, err = c.RateLimit(req)
if err != nil {
return res, errors.Wrap(err, "can't execute api request")
}
err = c.saveToCache(res)
*/
return res, errors.Wrap(err, "can't cache api response")
}
func (c *APIClient) Get(rsrc string, args url.Values) (*http.Response, error) {
u, err := c.BaseURL.Parse(rsrc)
if err != nil {
return nil, errors.Wrap(err, "can't parse api request uri " + rsrc)
}
if args != nil {
u.RawQuery = args.Encode()
}
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
return nil, errors.Wrap(err, "can't create api get request")
}
if c.Authenticator != nil {
err = c.Authenticator.AuthenticateRequest(req)
if err != nil {
return nil, errors.Wrap(err, "can't auth api get request")
}
}
return c.Do(req)
}
func (c *APIClient) GetObj(rsrc string, args url.Values, obj interface{}) error {
res, err := c.Get(rsrc, args)
if err != nil {
return errors.Wrap(err, "can't execute api get request")
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
return errors.New(res.Status)
}
ct := strings.Split(res.Header.Get("Content-Type"), ";")[0]
if ct != "application/json" {
return errors.Errorf("not a json response (%s)", ct)
}
data, err := ioutil.ReadAll(res.Body)
if err != nil {
return errors.Wrap(err, "can't read api response")
}
err = json.Unmarshal(data, obj)
if err != nil {
return errors.Wrapf(err, "can't unmarshal api response into %T", obj)
}
return nil
}