-
Notifications
You must be signed in to change notification settings - Fork 0
/
currency.go
71 lines (54 loc) · 1.35 KB
/
currency.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
package go_currency_codes
import (
"encoding/json"
"errors"
"crypto/sha256"
"fmt"
"strings"
"io"
)
// All returns all the currencies
func All() (map[string]interface{}, error) {
currencyMap, err := parse()
if err != nil {
return nil, err
}
return currencyMap, nil
}
// FromCurrencyName returns the currency details from the currency name
func FromCurrencyName(name string) (map[string]interface{}, error) {
if name == "" {
return nil, errors.New("empty currency name")
}
sha := sha256.New()
sha.Write([]byte(strings.TrimSpace(name)))
shaName := fmt.Sprintf("%x", sha.Sum(nil))
currencyMap, err := parse()
if err != nil {
return nil, err
}
detail, ok := currencyMap[shaName]
if !ok {
return nil, errors.New("currency name not found")
}
return detail.(map[string]interface{}), nil
}
// WriteJSON writes all the currencies to the given writer as a JSON string
func WriteJSON(indent int, writer io.Writer) error {
currencyMap, err := parse()
if err != nil {
return err
}
enc := json.NewEncoder(writer)
enc.SetIndent("", strings.Repeat(" ", indent))
return enc.Encode(currencyMap)
}
// parse encodes the world's currencies into a map
func parse() (map[string]interface{}, error) {
var currencyMap map[string]interface{}
err := json.Unmarshal([]byte(Data), ¤cyMap)
if err != nil {
return nil, err
}
return currencyMap, nil
}