Skip to content

Commit

Permalink
Fix data race when calling GetISO3166
Browse files Browse the repository at this point in the history
The data race was triggered when multiple goroutines
tried to access and modify the global variable used for caching ISO3166
per-country configurations.
  • Loading branch information
georgepsarakis committed Oct 4, 2023
1 parent 2aa619e commit b3ac1c1
Showing 1 changed file with 15 additions and 5 deletions.
20 changes: 15 additions & 5 deletions iso3166.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,27 @@ type ISO3166 struct {
PhoneNumberLengths []int
}

func init() {
// Run once during package initialization in order to avoid data races
// https://go.dev/doc/effective_go#init
populateISO3166()
}

var iso3166Datas []ISO3166

// GetISO3166 ...
// GetISO3166 returns the ISO3166 configuration for each country.
// Data are loaded during package initialization.
func GetISO3166() []ISO3166 {
return iso3166Datas
}

// populateISO3166 contains the definitions of the per-country mobile number configuration.
// It operates on the iso3166Datas global variable and will return it after population.
func populateISO3166() {
if iso3166Datas != nil {
return iso3166Datas
return
}

iso3166Datas = []ISO3166{}
var i = ISO3166{}

i.Alpha2 = "US"
Expand Down Expand Up @@ -1871,6 +1883,4 @@ func GetISO3166() []ISO3166 {
i.MobileBeginWith = []string{"71", "73", "77"}
i.PhoneNumberLengths = []int{9}
iso3166Datas = append(iso3166Datas, i)

return iso3166Datas
}

0 comments on commit b3ac1c1

Please sign in to comment.