-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdinero.go
207 lines (173 loc) · 4.97 KB
/
dinero.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
package dinero
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"time"
cache "github.com/patrickmn/go-cache"
)
const (
packageVersion = "0.8.0"
backendURL = "https://openexchangerates.org"
userAgent = "dinero/" + packageVersion
)
var (
// ErrRatesNotFound is returned if no rate can be found for a given currency code.
ErrRatesNotFound = errors.New("no rates found for code")
)
// Client holds a connection to the OXR API.
type Client struct {
// client is the HTTP client the package will use for requests.
client *http.Client
// AppID is the Open Exchange Rates application ID.
AppID string
// UserAgent is the UA for this package that all requests will use.
UserAgent string
// BackendURL is the base API endpoint at OXR.
BackendURL *url.URL
// Services used for communicating with the API.
Rates *RatesService
HistoricalRates *HistoricalRatesService
Currencies *CurrenciesService
Cache *CacheService
}
// NewClient creates a new Client with the appropriate connection details and
// services used for communicating with the API.
func NewClient(appID, baseCurrency string, expiry time.Duration) *Client {
// Init new http.Client.
httpClient := http.DefaultClient
// Parse BE URL.
baseURL, _ := url.Parse(backendURL)
c := &Client{
client: httpClient,
BackendURL: baseURL,
UserAgent: userAgent,
AppID: appID,
}
// Init a new store.
store := cache.New(expiry, 10*time.Minute)
// Init services.
c.Rates = NewRatesService(c, baseCurrency)
c.HistoricalRates = NewHistoricalRatesService(c, baseCurrency)
c.Currencies = NewCurrenciesService(c)
c.Cache = NewCacheService(c, store)
return c
}
// NewRequest creates an authenticated API request. A relative URL can be provided in urlPath,
// which will be resolved to the BackendURL of the Client.
func (c *Client) NewRequest(method, urlPath string, params url.Values, body interface{}) (*http.Request, error) {
// make sure rendered URL is correct whether we have other params than app_id or not
params.Set("app_id", c.AppID)
// Parse our URL.
rel, err := url.Parse(
fmt.Sprintf("/api/%s?%s", urlPath, params.Encode()),
)
if err != nil {
return nil, err
}
return c.request(method, rel, body)
}
// NewUnauthedRequest creates an unauthenticated API request. A relative URL can be provided in urlPath,
// which will be resolved to the BackendURL of the Client.
func (c *Client) NewUnauthedRequest(method, urlPath string, body interface{}) (*http.Request, error) {
// Parse our URL.
rel, err := url.Parse(
fmt.Sprintf("/api/%s", urlPath),
)
if err != nil {
return nil, err
}
return c.request(method, rel, body)
}
func (c *Client) request(method string, rel *url.URL, body interface{}) (*http.Request, error) {
// Resolve to absolute URI.
u := c.BackendURL.ResolveReference(rel)
buf := new(bytes.Buffer)
if body != nil {
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
// Create the request.
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
// Add our libraries UA.
req.Header.Add("User-Agent", c.UserAgent)
return req, nil
}
// Do sends an API request and returns the API response. The API response is
// JSON decoded and stored in 'v', or returned as an error if an API (if found).
func (c *Client) Do(req *http.Request, v interface{}) (*Response, error) {
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer func() {
if rerr := resp.Body.Close(); err == nil {
err = rerr
}
}()
// Wrap our response.
response := &Response{Response: resp}
// Check for any errors that may have occurred.
err = CheckResponse(resp)
if err != nil {
return response, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
_, err = io.Copy(w, resp.Body)
if err != nil {
return nil, err
}
} else {
err = json.NewDecoder(resp.Body).Decode(&v)
if err != nil {
return nil, err
}
}
}
return response, err
}
// Response is a OXR response. This wraps the standard http.Response
// returned from the OXR API.
type Response struct {
*http.Response
ErrorCode int64
Message string
}
// An ErrorResponse reports the error caused by an API request
type ErrorResponse struct {
*http.Response
ErrorCode int64 `json:"status"`
Message string `json:"message"`
Description string `json:"description"`
}
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%d %v", r.Response.StatusCode, r.Description)
}
// CheckResponse checks the API response for errors. A response is considered an
// error if it has a status code outside the 200 range. API error responses map
// to ErrorResponse.
func CheckResponse(r *http.Response) error {
if c := r.StatusCode; c >= 200 && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{Response: r}
data, err := ioutil.ReadAll(r.Body)
if err == nil && len(data) > 0 {
err := json.Unmarshal(data, errorResponse)
if err != nil {
return err
}
}
return errorResponse
}