-
Notifications
You must be signed in to change notification settings - Fork 10
/
getURL.go
58 lines (49 loc) · 1.53 KB
/
getURL.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
package imgur
import (
"errors"
"io/ioutil"
"net/http"
)
func (client *Client) createAPIURL(u string) string {
if client.rapidAPIKey == "" {
return apiEndpoint + u
}
return apiEndpointRapidAPI + u
}
// getURL returns
// - body as string
// - RateLimit with current limits
// - error in case something broke
func (client *Client) getURL(URL string) (string, *RateLimit, error) {
URL = client.createAPIURL(URL)
client.Log.Infof("Requesting URL %v\n", URL)
req, err := http.NewRequest("GET", URL, nil)
if err != nil {
return "", nil, errors.New("Could not create request for " + URL + " - " + err.Error())
}
req.Header.Add("Authorization", "Client-ID "+client.imgurAccount.clientID)
if client.rapidAPIKey != "" {
req.Header.Add("x-rapidapi-host", "imgur-apiv3.p.rapidapi.com")
req.Header.Add("x-rapidapi-key", client.rapidAPIKey)
}
// Make a request to the sourceURL
res, err := client.httpClient.Do(req)
if err != nil {
return "", nil, errors.New("Could not get " + URL + " - " + err.Error())
}
defer res.Body.Close()
if !(res.StatusCode >= 200 && res.StatusCode <= 300) {
return "", nil, errors.New("HTTP status indicates an error for " + URL + " - " + res.Status)
}
// Read the whole body
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", nil, errors.New("Problem reading the body for " + URL + " - " + err.Error())
}
// Get RateLimit headers
rl, err := extractRateLimits(res.Header)
if err != nil {
client.Log.Infof("Problem with extracting rate limits: %v", err)
}
return string(body[:]), rl, nil
}