-
Notifications
You must be signed in to change notification settings - Fork 4
/
api.go
94 lines (75 loc) · 1.71 KB
/
api.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
package nationbuilder
import (
"fmt"
"net/http"
"net/url"
"strconv"
)
const apiVersion = "v1"
const debug = false
const defaultLimit = 50
type nationbuilderURL struct {
u url.URL
}
func (n *nationbuilderURL) setQuery(key string, val string) {
q := n.u.Query()
q.Set(key, val)
n.u.RawQuery = q.Encode()
}
func (n *nationbuilderURL) setLimit(limit int) {
n.setQuery("limit", strconv.Itoa(limit))
}
func (n *nationbuilderURL) setToken(token string) {
n.setQuery("access_token", token)
}
func (n *nationbuilderURL) extendPath(path string) {
if len(path) > 0 {
if string(path[0]) != "/" {
n.u.Path += "/"
}
n.u.Path += path
}
}
func (n *nationbuilderURL) String() string {
return n.u.String()
}
type Client struct {
Slug string
ApiKey string
baseURL *nationbuilderURL
c *http.Client
}
func (n *Client) getRequest(method string, path string, options *Options) *apiRequest {
b := *n.baseURL
b.extendPath(path)
if options != nil {
options.setQuery(&b.u)
}
return &apiRequest{
url: b.String(),
method: method,
}
}
// By default http.DefaultClient is used to make requests but if you need to set additional options
// such as a proxy or you are running on Google App Engine, then you may want to supply a different
// http client
func (n *Client) SetHTTPClient(c *http.Client) {
n.c = c
}
// Creates a new Nationbuilder Client
func NewClient(slug string, key string) (*Client, error) {
u, err := url.Parse(fmt.Sprintf("https://%s.nationbuilder.com/api/%s", slug, apiVersion))
if err != nil {
return nil, err
}
nbURL := &nationbuilderURL{
u: *u,
}
nbURL.setToken(key)
return &Client{
Slug: slug,
ApiKey: key,
baseURL: nbURL,
c: http.DefaultClient,
}, nil
}