Skip to content

Commit

Permalink
Add mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
kolomiichenko committed Mar 14, 2017
1 parent 762c14d commit 6beff20
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ package main

import (
"gopkg.in/kolomiichenko/cbr-currency-go.v1"
"log"
"fmt"
)

func main() {
cbr.updateCurrency() // force update
log.Println(cbr.CurrencyRates["USD"])
rates := cbr.GetCurrencyRates()
fmt.Printf("%+v\n", rates["USD"])
}
```

Expand Down
20 changes: 16 additions & 4 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"
"strconv"
"strings"
"sync"
"time"

"golang.org/x/net/html/charset"
Expand Down Expand Up @@ -35,8 +36,10 @@ type currencyRate struct {
Value float64
}

// CurrencyRates Global map with rates
var CurrencyRates map[string]currencyRate
var (
currencyRates map[string]currencyRate
mu sync.Mutex
)

func init() {
UpdateCurrencyRates()
Expand All @@ -49,6 +52,11 @@ func doEvery(d time.Duration, f func()) {
}
}

// GetCurrencyRates Get map of rates
func GetCurrencyRates() map[string]currencyRate {
return currencyRates
}

// UpdateCurrencyRates To sync rates from CBR server
func UpdateCurrencyRates() {
resp, err := http.Get("http://www.cbr.ru/scripts/XML_daily.asp")
Expand All @@ -66,17 +74,21 @@ func UpdateCurrencyRates() {
return
}

CurrencyRates = make(map[string]currencyRate)
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{
currencyRates[el.CharCode] = currencyRate{
ID: el.ID,
NumCode: el.NumCode,
ISOCode: el.CharCode,
Name: el.Name,
Value: value / el.Nominal,
}
}

defer mu.Unlock()
}

0 comments on commit 6beff20

Please sign in to comment.