-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfinanceapi.go
69 lines (58 loc) · 1.62 KB
/
financeapi.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
// Author(s): Michael Koeppl
package dinero
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/shopspring/decimal"
)
const (
url = "http://rate-exchange-1.appspot.com/currency?from=%s&to=%s"
timeout = time.Second * 5
)
// Result represents the JSON response from the ExchangeRates API.
type result struct {
// The ",string" part tells json's Unmarshal function
// that Rate is a string encoded float.
Rate float64 `json:"rate"`
From string `json:"from"`
To string `json:"to"`
}
// URL generates a URL for querying the ExchangeRates API.
func URL(from, to string) string {
return fmt.Sprintf(url, from, to)
}
// Returns a custom client with timeout set to 5 seconds. This ensures
// that the library doesn't make an app freeze.
func customClient() *http.Client {
cc := &http.Client{
Timeout: timeout,
}
return cc
}
// Sends a GET request to the ExchangeRates API and returns
// the response containing the relevant fields.
func queryAPI(from, to string) (*result, error) {
apiResult := &result{}
response, err := customClient().Get(URL(from, to))
if err != nil {
return nil, err
}
buf, _ := ioutil.ReadAll(response.Body)
if err := json.Unmarshal(buf, &apiResult); err != nil {
return nil, err
}
return apiResult, nil
}
// rate is sort of a convenience function to quickly fetch the most
// recent exchance rate from the ExchangeRates API.
// It returns only the exchance rate and any error that might occur.
func rate(from, to string) (decimal.Decimal, error) {
res, err := queryAPI(from, to)
if err != nil {
return decimal.Zero, err
}
return decimal.NewFromFloat(res.Rate), nil
}