-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
100 lines (83 loc) · 1.92 KB
/
main.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
package cbr
import (
"encoding/xml"
"log"
"net/http"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/net/html/charset"
)
type xmlResult struct {
ValCurs xml.Name `xml:"ValCurs"`
Date string `xml:"Date,attr"`
Name string `xml:"name,attr"`
Valute []valute `xml:"Valute"`
}
type valute struct {
ID string `xml:"ID,attr"`
NumCode int64 `xml:"NumCode"`
CharCode string `xml:"CharCode"`
Nominal float64 `xml:"Nominal"`
Name string `xml:"Name"`
Value string `xml:"Value"`
}
type currencyRate struct {
ID string
NumCode int64
ISOCode string
Name string
Value float64
}
var (
currencyRates map[string]currencyRate
mu sync.Mutex
)
func init() {
UpdateCurrencyRates()
go doEvery(1*time.Hour, UpdateCurrencyRates)
}
func doEvery(d time.Duration, f func()) {
for range time.Tick(d) {
f()
}
}
// GetCurrencyRates Get map of rates
func GetCurrencyRates() map[string]currencyRate {
return currencyRates
}
// UpdateCurrencyRates To sync rates from CBR server
// original URL (http://www.cbr.ru/scripts/XML_daily.asp) changed
// to unofficial mirror (https://www.cbr-xml-daily.ru/daily.xml)
func UpdateCurrencyRates() {
client := &http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Get("https://www.cbr-xml-daily.ru/daily.xml")
if err != nil {
log.Printf("Error of get currency: %v", err.Error())
return
}
var data xmlResult
decoder := xml.NewDecoder(resp.Body)
decoder.CharsetReader = charset.NewReaderLabel
err = decoder.Decode(&data)
if err != nil {
log.Printf("error: %v", err)
return
}
mu.Lock()
currencyRates = make(map[string]currencyRate)
for _, el := range data.Valute {
value, _ := strconv.ParseFloat(strings.Replace(el.Value, ",", ".", -1), 64)
currencyRates[el.CharCode] = currencyRate{
ID: el.ID,
NumCode: el.NumCode,
ISOCode: el.CharCode,
Name: el.Name,
Value: value / el.Nominal,
}
}
defer mu.Unlock()
}