From b3ac1c10df6732dbacc78b560796f69e9e7b67b5 Mon Sep 17 00:00:00 2001 From: George Psarakis Date: Wed, 4 Oct 2023 11:16:29 +0300 Subject: [PATCH] Fix data race when calling GetISO3166 The data race was triggered when multiple goroutines tried to access and modify the global variable used for caching ISO3166 per-country configurations. --- iso3166.go | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/iso3166.go b/iso3166.go index 2ddb4ea..ce4590b 100644 --- a/iso3166.go +++ b/iso3166.go @@ -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" @@ -1871,6 +1883,4 @@ func GetISO3166() []ISO3166 { i.MobileBeginWith = []string{"71", "73", "77"} i.PhoneNumberLengths = []int{9} iso3166Datas = append(iso3166Datas, i) - - return iso3166Datas }