-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
65 lines (58 loc) · 1.27 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
package countrycode
import (
"strings"
)
// https://www.iban.com/country-codes
// Constants
const (
Alpha2 string = "ALPHA2"
Alpha3 string = "ALPHA3"
Numeric string = "NUMERIC"
)
// Country defines the Country struct containing the Alpha2, Alpha3 and Numeric ISO codes
type Country struct {
Alpha2 string
Alpha3 string
Numeric string
}
// Convert returns the converted ISO code string or an error
func Convert(code string, format string) (string, error) {
country, err := getCountry(code)
if err != nil {
return "", err
}
convertedCode, err := getFormat(country, format)
if err != nil {
return "", err
}
return convertedCode, nil
}
func getCountry(code string) (Country, error) {
code = strings.ToUpper(code)
for _, country := range Countries {
switch code {
case country.Alpha2:
return country, nil
case country.Alpha3:
return country, nil
case country.Numeric:
return country, nil
default:
continue
}
}
return Country{}, ErrInvalidCountryCode
}
func getFormat(country Country, format string) (string, error) {
format = strings.ToUpper(format)
switch format {
case Alpha2:
return country.Alpha2, nil
case Alpha3:
return country.Alpha3, nil
case Numeric:
return country.Numeric, nil
default:
return "", ErrInvalidFormat
}
}