This repository has been archived by the owner on Apr 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
requests.go
72 lines (57 loc) · 1.43 KB
/
requests.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
package gocurrency
import (
"github.com/beevik/etree"
"strconv"
"net/http"
"log"
"time"
)
const (
RatesSource = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"
CacheExpire = time.Hour * 4
)
var (
ExchangeRates = make(map[string]float64)
CacheTime time.Time
)
func init() {
ExchangeRates["EUR"] = 1 //EUR doesn't exist by default, because values are relative to EUR
}
func RefreshRates() {
resp, err := http.Get(RatesSource)
defer func() {
if r := recover(); r != nil {
updateError(r.(error))
}
}()
if err != nil {
panic(err)
}
root := etree.NewDocument()
if _, err := root.ReadFrom(resp.Body); err != nil {
panic(err)
}
for _, v := range selectRecursive(root.Element, "gesmes:Envelope", "Cube", "Cube", "Cube"){
rate, _ := strconv.ParseFloat(v.SelectAttr("rate").Value, 32)
ExchangeRates[v.SelectAttr("currency").Value] = rate
}
CacheTime = time.Now()
}
func RefreshIfRequired() {
if CacheTime.Add(CacheExpire).Before(time.Now()) {
RefreshRates()
}
}
func updateError(err error) {
if CacheTime.IsZero() {
log.Panicf("Unable to update exchange rates. Error: \n%v", err)
}
log.Printf("<IMPORTANT> Unable to update exchange rates. Current rates are from %v", CacheTime)
}
func selectRecursive(elem etree.Element, path ...string) ([]*etree.Element) {
relem := &elem
for _, v := range path[:len(path) - 1] {
relem = relem.SelectElement(v)
}
return relem.SelectElements(path[len(path) - 1])
}