-
Notifications
You must be signed in to change notification settings - Fork 133
/
fx.go
178 lines (141 loc) · 3.44 KB
/
fx.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
// fx does Foreign Exchange / currency conversions.
package fx
import (
"bytes"
"encoding/gob"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
const apiURL = "https://api.exchangerate.host/latest"
var reParse = regexp.MustCompile("([0-9\\.]+)([A-Z]{3})\\-([A-Z]{3})")
// FX represents the currency coversion (Foreign Exchange) package.
type FX struct {
opt Opt
data data
mut sync.RWMutex
}
type data struct {
Base string `json:"base"`
Date string `json:"date"`
Rates map[string]float64 `json:"rates"`
}
// Opt represents the config options for the FX converter.
type Opt struct {
RefreshInterval time.Duration `json:"refresh_interval"`
}
// New returns an instace of the FX converter.
func New(o Opt) *FX {
fx := &FX{
opt: o,
}
// Periodically fetch and refresh the rates.
go func() {
for {
log.Println("loading fx API")
d, err := fx.load(apiURL)
if err != nil {
log.Printf("error loading fx rates API: %v", err)
// HTTP fetch failed. Retry again in a minute.
time.Sleep(time.Minute)
continue
}
if _, ok := d.Rates[d.Base]; !ok {
log.Printf("base currency %s not found in rates", d.Base)
time.Sleep(time.Minute * 5)
continue
}
log.Printf("%d fx currency pairs loaded", len(d.Rates))
fx.mut.Lock()
fx.data = d
fx.mut.Unlock()
time.Sleep(o.RefreshInterval)
}
}()
return fx
}
// Query handles a currency rate conversion query.
// Format: 100USD-INR.FX
func (fx *FX) Query(q string) ([]string, error) {
if len(fx.data.Rates) == 0 {
return nil, errors.New("fx data unavailable. Please try later.")
}
q = strings.ToUpper(q)
res := reParse.FindStringSubmatch(q)
if len(res) != 4 {
return nil, errors.New("invalid fx query.")
}
// Parse the numeric value.
val, err := strconv.ParseFloat(res[1], 32)
if err != nil {
return nil, errors.New("invalid number.")
}
var (
from = res[2]
to = res[3]
)
// Validate the currency names.
fx.mut.RLock()
fromRate, ok := fx.data.Rates[from]
fx.mut.RUnlock()
if !ok {
return nil, fmt.Errorf("unknown from currency '%s'.", from)
}
toRate, ok := fx.data.Rates[to]
if !ok {
return nil, fmt.Errorf("unknown to currency '%s'.", to)
}
baseRate := fx.data.Rates[fx.data.Base]
// Convert.
conv := (baseRate / fromRate) / (baseRate / toRate) * val
r := fmt.Sprintf("%s TXT \"%0.2f %s = %0.2f %s\" \"%s\"", q, val, from, conv, to, fx.data.Date)
return []string{r}, nil
}
// Dump produces a gob dump of the cached data.
func (fx *FX) Dump() ([]byte, error) {
buf := &bytes.Buffer{}
fx.mut.RLock()
defer fx.mut.RUnlock()
if err := gob.NewEncoder(buf).Encode(fx.data); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// Load loads a gob dump of cached data.
func (fx *FX) Load(b []byte) error {
buf := bytes.NewBuffer(b)
fx.mut.RLock()
defer fx.mut.RUnlock()
err := gob.NewDecoder(buf).Decode(&fx.data)
return err
}
func (fx *FX) load(url string) (data, error) {
client := http.Client{
Timeout: 6 * time.Second,
}
req, _ := http.NewRequest("GET", url, nil)
resp, err := client.Do(req)
if err != nil {
return data{}, err
}
if resp.StatusCode != http.StatusOK {
return data{}, fmt.Errorf("request failed: %v", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return data{}, err
}
var out data
if err := json.Unmarshal(body, &out); err != nil {
return data{}, err
}
return out, nil
}