-
Notifications
You must be signed in to change notification settings - Fork 3
/
country.go
109 lines (80 loc) · 2.34 KB
/
country.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
package country
import (
"encoding/json"
"io/ioutil"
"path/filepath"
)
// Country struct
type Country struct {
data map[string]interface{}
}
// NewCountry will create a new instance of country struct
func NewCountry() *Country {
instance := &Country{}
instance = instance.readCountriesDataFile()
return instance
}
// Read countries data file
func (country *Country) readCountriesDataFile() *Country {
if len(country.data) > 0 {
return country
}
dataPath, _ := filepath.Abs("./data/countries.json")
file, _ := ioutil.ReadFile(dataPath)
json.Unmarshal([]byte(file), &country.data)
return country
}
// All will return all countries name and dialing code
func (country *Country) All() map[string]interface{} {
return country.readCountriesDataFile().data
}
// Get a single country by the country ISO 3166-1 Alpha-2 code
func (country *Country) getCountry(code string) (interface{}, error) {
details := country.readCountriesDataFile().data[code]
if details == nil {
return nil, NewValidationError(code)
}
return details, nil
}
// Get a country name and dialing code by the country ISO 3166-1 Alpha-2 code
func (country *Country) Get(code interface{}) (interface{}, error) {
switch code.(type) {
case string:
return country.getCountry(code.(string))
case []string:
data, err := country.gets(code.([]string))
return data, err
default:
return nil, nil
}
}
// GetName will return a country name by the country ISO 3166-1 Alpha-2 code
func (country *Country) GetName(code string) (interface{}, error) {
data, err := country.getCountry(code)
if err != nil {
return nil, err
}
details, _ := data.(map[string]interface{})
return details["name"], nil
}
// GetDialingCode will return a country dialing code by the country ISO 3166-1 Alpha-2 code
func (country *Country) GetDialingCode(code string) (interface{}, error) {
data, err := country.getCountry(code)
if err != nil {
return nil, err
}
details, _ := data.(map[string]interface{})
return details["code"], nil
}
// Get countries name and dialing code by the country ISO 3166-1 Alpha-2 codes
func (country *Country) gets(codes []string) (map[string]interface{}, error) {
countries := make(map[string]interface{})
for _, code := range codes {
details, err := country.getCountry(code)
if err != nil {
return nil, err
}
countries[code] = details
}
return countries, nil
}