-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrequest.go
84 lines (71 loc) · 1.8 KB
/
request.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
package poeapi
import (
"io/ioutil"
"net/http"
"strings"
)
type requestFunc func(string) (string, error)
// Get is a helper function which includes caching and ratelimiting for outbound
// requests.
func (c *client) get(url string) (string, error) {
return c.withCache(url, c.withRateLimit(url, c.getJSON))
}
// getJSON retrieves the given URL. It returns the JSON response as a string.
func (c *client) getJSON(url string) (string, error) {
resp, err := c.httpClient.Get(url)
if err != nil {
// An error is returned if the Client's CheckRedirect function fails or
// if there was an HTTP protocol error. A non-2xx response doesn't cause
// an error.
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", parseError(resp.StatusCode)
}
b, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(b), nil
}
func (c *client) withCache(url string, fn requestFunc) (string, error) {
if !c.useCache {
return fn(url)
}
// Disable caching for stash endpoint.
if strings.HasPrefix(url, c.formatURL(stashTabsEndpoint)) {
return fn(url)
}
if cached, err := c.cache.Get(url); err == nil {
return cached, nil
}
resp, err := fn(url)
if err != nil {
return "", err
}
c.cache.Set(url, resp)
return resp, nil
}
func (c *client) withRateLimit(url string, fn requestFunc) requestFunc {
if strings.HasPrefix(url, c.formatURL(stashTabsEndpoint)) {
c.limiter.Wait(true)
return fn
}
c.limiter.Wait(false)
return fn
}
func parseError(statusCode int) error {
switch statusCode {
case http.StatusBadRequest:
return ErrBadRequest
case http.StatusNotFound:
return ErrNotFound
case http.StatusTooManyRequests:
return ErrRateLimited
case http.StatusInternalServerError:
return ErrServerFailure
default:
return ErrUnknownFailure
}
}