-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitballoon.go
288 lines (237 loc) · 6.34 KB
/
bitballoon.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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
package bitballoon
import (
"bytes"
"code.google.com/p/goauth2/oauth"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
"path"
"strconv"
"strings"
)
const (
libraryVersion = "0.1"
defaultBaseURL = "https://www.bitballoon.com"
apiVersion = "v1"
userAgent = "bitballoon-go/" + libraryVersion
)
// Config is used to configure the BitBalloon client.
// Typically you'll just want to set an AccessToken
type Config struct {
AccessToken string
ClientId string
ClientSecret string
BaseUrl string
UserAgent string
HttpClient *http.Client
}
// The BitBalloon Client
type Client struct {
client *http.Client
BaseUrl *url.URL
UserAgent string
Sites *SitesService
Deploys *DeploysService
}
// BitBalloon API Response.
// All API methods on the different client services will return a Response object.
// For any list operation this object will hold pagination information
type Response struct {
*http.Response
NextPage int
PrevPage int
FirstPage int
LastPage int
}
// RequestOptions for doing raw requests to the BitBalloon API
type RequestOptions struct {
JsonBody interface{}
RawBody io.Reader
RawBodyLength int64
QueryParams *url.Values
Headers *map[string]string
}
// ErrorResponse is returned when a request to the API fails
type ErrorResponse struct {
Response *http.Response
Message string
}
// All List methods takes a ListOptions object controlling pagination
type ListOptions struct {
Page int
PerPage int
}
func (o *ListOptions) toQueryParamsMap() *url.Values {
params := url.Values{}
if o.Page > 0 {
params["page"] = []string{strconv.Itoa(o.Page)}
}
if o.PerPage > 0 {
params["per_page"] = []string{strconv.Itoa(o.PerPage)}
}
return ¶ms
}
func (r *ErrorResponse) Error() string {
return r.Message
}
// NewClient returns a new BitBalloon API client
func NewClient(config *Config) *Client {
client := &Client{}
if config.BaseUrl != "" {
client.BaseUrl, _ = url.Parse(config.BaseUrl)
} else {
client.BaseUrl, _ = url.Parse(defaultBaseURL)
}
if config.HttpClient != nil {
client.client = config.HttpClient
} else if config.AccessToken != "" {
t := &oauth.Transport{
Token: &oauth.Token{AccessToken: config.AccessToken},
}
client.client = t.Client()
}
if &config.UserAgent != nil {
client.UserAgent = config.UserAgent
} else {
client.UserAgent = userAgent
}
client.Sites = &SitesService{client: client}
client.Deploys = &DeploysService{client: client}
return client
}
func (c *Client) newRequest(method, apiPath string, options *RequestOptions) (*http.Request, error) {
if c.client == nil {
return nil, errors.New("Client has not been authenticated")
}
urlPath := path.Join("api", apiVersion, apiPath)
if options != nil && options.QueryParams != nil && len(*options.QueryParams) > 0 {
urlPath = urlPath + "?" + options.QueryParams.Encode()
}
rel, err := url.Parse(urlPath)
if err != nil {
return nil, err
}
u := c.BaseUrl.ResolveReference(rel)
buf := new(bytes.Buffer)
if options != nil && options.JsonBody != nil {
err := json.NewEncoder(buf).Encode(options.JsonBody)
if err != nil {
return nil, err
}
}
var req *http.Request
if options != nil && options.RawBody != nil {
req, err = http.NewRequest(method, u.String(), options.RawBody)
req.ContentLength = options.RawBodyLength
} else {
req, err = http.NewRequest(method, u.String(), buf)
}
if err != nil {
return nil, err
}
req.TransferEncoding = []string{"identity"}
req.Header.Add("Accept", "application/json")
req.Header.Add("User-Agent", c.UserAgent)
if options != nil && options.JsonBody != nil {
req.Header.Set("Content-Type", "application/json")
}
if options != nil && options.Headers != nil {
for key, value := range *options.Headers {
req.Header.Set(key, value)
}
}
return req, nil
}
// Request sends an authenticated HTTP request to the BitBalloon API
//
// When error is nil, resp always contains a non-nil Response object
//
// Generally methods on the various services should be used over raw API requests
func (c *Client) Request(method, path string, options *RequestOptions, decodeTo interface{}) (*Response, error) {
req, err := c.newRequest(method, path, options)
if err != nil {
return nil, err
}
httpResponse, err := c.client.Do(req)
resp := newResponse(httpResponse)
if err != nil {
return resp, err
}
if err = checkResponse(httpResponse); err != nil {
return resp, err
}
if decodeTo != nil {
defer httpResponse.Body.Close()
if writer, ok := decodeTo.(io.Writer); ok {
io.Copy(writer, httpResponse.Body)
} else {
err = json.NewDecoder(httpResponse.Body).Decode(decodeTo)
}
}
return resp, err
}
func newResponse(r *http.Response) *Response {
response := &Response{Response: r}
if r != nil {
response.populatePageValues()
}
return response
}
func checkResponse(r *http.Response) error {
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{Response: r}
if r.StatusCode == 403 || r.StatusCode == 401 {
errorResponse.Message = "Access Denied"
return errorResponse
}
data, err := ioutil.ReadAll(r.Body)
if err == nil && data != nil {
errorResponse.Message = string(data)
} else {
errorResponse.Message = r.Status
}
return errorResponse
}
// populatePageValues parses the HTTP Link response headers and populates the
// various pagination link values in the Reponse.
func (r *Response) populatePageValues() {
if links, ok := r.Response.Header["Link"]; ok && len(links) > 0 {
for _, link := range strings.Split(links[0], ",") {
segments := strings.Split(strings.TrimSpace(link), ";")
// link must at least have href and rel
if len(segments) < 2 {
continue
}
// ensure href is properly formatted
if !strings.HasPrefix(segments[0], "<") || !strings.HasSuffix(segments[0], ">") {
continue
}
// try to pull out page parameter
url, err := url.Parse(segments[0][1 : len(segments[0])-1])
if err != nil {
continue
}
page := url.Query().Get("page")
if page == "" {
continue
}
for _, segment := range segments[1:] {
switch strings.TrimSpace(segment) {
case `rel="next"`:
r.NextPage, _ = strconv.Atoi(page)
case `rel="prev"`:
r.PrevPage, _ = strconv.Atoi(page)
case `rel="first"`:
r.FirstPage, _ = strconv.Atoi(page)
case `rel="last"`:
r.LastPage, _ = strconv.Atoi(page)
}
}
}
}
}