-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathclient.go
93 lines (73 loc) · 1.75 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
package mapbox
import (
"encoding/json"
"io"
"net/http"
"net/url"
"regexp"
"strings"
"time"
"github.com/pkg/errors"
)
type SortBy string
const (
SortByCreated SortBy = "created"
SortByModified SortBy = "modified"
)
type Client struct {
username string
token string
baseURL url.URL
HttpClient *http.Client
}
func NewClient(username, token string) *Client {
baseURL, _ := url.Parse("https://api.mapbox.com")
httpClient := http.Client{
Timeout: 15 * time.Second,
}
return &Client{
username: username,
token: token,
baseURL: *baseURL,
HttpClient: &httpClient,
}
}
func (c *Client) do(method string, url url.URL, body io.Reader, value interface{}) (*http.Response, error) {
url = c.addAuthentication(url)
req, err := http.NewRequest(method, url.String(), body)
if err != nil {
return nil, errors.Wrap(err, "creating request")
}
resp, err := c.HttpClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "requesting")
}
defer resp.Body.Close()
err = json.NewDecoder(resp.Body).Decode(value)
if err != nil {
return nil, errors.Wrap(err, "decoding json")
}
return resp, nil
}
// addAuthentication adds an authentication token to the URL.
func (c *Client) addAuthentication(url url.URL) url.URL {
q := url.Query()
q.Add("access_token", c.token)
url.RawQuery = q.Encode()
return url
}
// nextPageURL finds the link pointing to the next page of data in the header,
// and adds authentication.
func (c *Client) nextPageURL(header http.Header) *url.URL {
nextRegex := regexp.MustCompile("<(.*)>")
link := header.Get("Link")
if strings.Contains(link, "next") {
requestURL, err := url.Parse(nextRegex.FindStringSubmatch(link)[1])
if err != nil {
return nil
}
return requestURL
} else {
return nil
}
}