git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/countries/countries.go (about) 1 package countries 2 3 import ( 4 _ "embed" 5 "encoding/json" 6 "errors" 7 "fmt" 8 ) 9 10 //go:embed countries.json 11 var Bytes []byte 12 13 const ( 14 Unknown = "Unknown" 15 CodeUnknown = "XX" 16 ) 17 18 type Country struct { 19 Name string `json:"name"` 20 Code string `json:"code"` 21 } 22 23 var countriesMap map[string]Country 24 var countriesList []Country 25 26 var ( 27 ErrCountryNotFound = errors.New("Country not found") 28 ) 29 30 func Init() (err error) { 31 countriesList = []Country{} 32 33 err = json.Unmarshal(Bytes, &countriesList) 34 if err != nil { 35 return fmt.Errorf("countries: error decoding JSON: %w", err) 36 } 37 38 countriesMap = map[string]Country{} 39 for _, country := range countriesList { 40 if _, exists := countriesMap[country.Code]; exists { 41 err = fmt.Errorf("countries: ducplicate country for country code: %s", country.Code) 42 return 43 } 44 45 countriesMap[country.Code] = country 46 } 47 48 return 49 } 50 51 func GetMap() map[string]Country { 52 return countriesMap 53 } 54 55 func GetList() []Country { 56 return countriesList 57 } 58 59 func Name(countryCode string) (countryName string, err error) { 60 countryName = Unknown 61 62 country, exists := countriesMap[countryCode] 63 if !exists { 64 err = ErrCountryNotFound 65 return 66 } 67 68 countryName = country.Name 69 return 70 }