-
Notifications
You must be signed in to change notification settings - Fork 1
/
brewerydb.go
201 lines (181 loc) · 5.02 KB
/
brewerydb.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
// Copyright 2015 Joseph Naegele. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package brewerydb provides bindings to the BreweryDB API
// (http://www.brewerydb.com)
package brewerydb
import (
"bytes"
"encoding/json"
"fmt"
"github.com/google/go-querystring/query"
"io"
"net/http"
"net/url"
"strconv"
)
// apiURL is not const so it can be stubbed in unit tests.
var apiURL = "http://api.brewerydb.com/v2"
// Page is a convenience type for encoding only a page number
// when paginating lists.
type Page struct {
P int `url:"p"`
}
// Images is a collection of up to three differently-sized image URLs.
type Images struct {
Icon string `url:"-"`
Medium string `url:"-"`
Large string `url:"-"`
}
// YesNo is just a bool that is url-encoded into either "Y" or "S".
type YesNo bool
// EncodeValues adds the value "Y" or "N" to the given url.Values
// for the given key if the YesNo value is true or false, respectively.
func (yn YesNo) EncodeValues(key string, v *url.Values) error {
if yn {
v.Set(key, "Y")
} else {
v.Set(key, "N")
}
return nil
}
// UnmarshalJSON decodes the JSON value "Y" or "N" into a boolean
// true or false, respectively.
func (yn *YesNo) UnmarshalJSON(data []byte) error {
// expect a single-rune string containing either 'Y' or 'N'
yes, no := []byte{'"', 'Y', '"'}, []byte{'"', 'N', '"'}
if bytes.Equal(data, yes) {
*yn = true
} else if bytes.Equal(data, no) {
*yn = false
} else {
return fmt.Errorf("invalid JSON value for YesNo (%v)", string(data))
}
return nil
}
// Client serves as the interface to the BreweryDB API.
type Client struct {
client http.Client
apiKey string
NumRequests int
JSONWriter io.Writer
Adjunct *AdjunctService
Beer *BeerService
Brewery *BreweryService
Category *CategoryService
Change *ChangeService
ConvertID *ConvertIDService
Event *EventService
Feature *FeatureService
Fermentable *FermentableService
Fluidsize *FluidsizeService
Glass *GlassService
Guild *GuildService
Heartbeat *HeartbeatService
Hop *HopService
Ingredient *IngredientService
Location *LocationService
Menu *MenuService
Search *SearchService
SocialSite *SocialSiteService
Style *StyleService
Yeast *YeastService
}
// NewClient creates a new BreweryDB Client using the given API key.
func NewClient(apiKey string) *Client {
c := &Client{}
c.apiKey = apiKey
c.Adjunct = &AdjunctService{c}
c.Beer = &BeerService{c}
c.Brewery = &BreweryService{c}
c.Category = &CategoryService{c}
c.Change = &ChangeService{c}
c.ConvertID = &ConvertIDService{c}
c.Event = &EventService{c}
c.Feature = &FeatureService{c}
c.Fermentable = &FermentableService{c}
c.Fluidsize = &FluidsizeService{c}
c.Glass = &GlassService{c}
c.Guild = &GuildService{c}
c.Heartbeat = &HeartbeatService{c}
c.Hop = &HopService{c}
c.Ingredient = &IngredientService{c}
c.Location = &LocationService{c}
c.Menu = &MenuService{c}
c.Search = &SearchService{c}
c.SocialSite = &SocialSiteService{c}
c.Style = &StyleService{c}
c.Yeast = &YeastService{c}
return c
}
// NewRequest creates a new http.Request with the given method,
// BreweryDB endpoint, and optionally a struct to be URL-encoded
// in the request.
func (c *Client) NewRequest(method string, endpoint string, data interface{}) (req *http.Request, err error) {
var u *url.URL
u, err = url.Parse(apiURL)
if err != nil {
return
}
u.Path += endpoint
var dataVals url.Values
if data != nil {
dataVals, err = query.Values(data)
if err != nil {
return
}
} else {
dataVals = url.Values{}
}
switch method {
case "GET":
fallthrough
case "DELETE":
dataVals.Set("key", c.apiKey)
u.RawQuery = dataVals.Encode()
req, err = http.NewRequest(method, u.String(), nil)
case "POST":
fallthrough
case "PUT":
q := url.Values{}
q.Set("key", c.apiKey)
u.RawQuery = q.Encode()
payload := dataVals.Encode()
body := bytes.NewBufferString(payload)
req, err = http.NewRequest(method, u.String(), body)
if err != nil {
return
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(payload)))
default:
err = fmt.Errorf("Unknown HTTP method: %s", method)
}
return
}
// Do performs the given http.Request and optionally
// decodes the JSON response into the given data struct.
func (c *Client) Do(req *http.Request, data interface{}) error {
// TODO: [DEBUGGING] fmt.Println(req.Method, req.URL)
resp, err := c.client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
// TODO: return a more useful error message
return fmt.Errorf("HTTP Error %d", resp.StatusCode)
}
c.NumRequests++
if data != nil {
var body io.Reader
// if the client has a JSONWriter, also dump JSON responses
if c.JSONWriter != nil {
body = io.TeeReader(resp.Body, c.JSONWriter)
} else {
body = resp.Body
}
err = json.NewDecoder(body).Decode(data)
}
return err
}