From ed3be1714bf0bd1e7577cbe8f25dd3bded47dc07 Mon Sep 17 00:00:00 2001 From: bastengao Date: Thu, 27 Aug 2020 16:10:25 +0800 Subject: [PATCH] Fix init queryInstance concurrent race --- query.go | 9 +++++---- query_test.go | 2 +- setup.go | 6 ++---- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/query.go b/query.go index 0f9b0cf..d22278a 100644 --- a/query.go +++ b/query.go @@ -2,17 +2,18 @@ package gountries import ( "strings" + "sync" ) // Query holds a reference to the QueryHolder struct -var queryInited = false +var queryInitOnce sync.Once var queryInstance *Query // Query contains queries for countries, cities, etc. type Query struct { - Countries map[string]Country - NameToAlpha2 map[string]string - Alpha3ToAlpha2 map[string]string + Countries map[string]Country + NameToAlpha2 map[string]string + Alpha3ToAlpha2 map[string]string NativeNameToAlpha2 map[string]string } diff --git a/query_test.go b/query_test.go index 9c4efb0..063f78a 100644 --- a/query_test.go +++ b/query_test.go @@ -151,7 +151,7 @@ func TestFindCountryByAlpha(t *testing.T) { func TestFindAllCountries(t *testing.T) { - assert.Len(t, query.FindAllCountries(), 247) + assert.Len(t, query.FindAllCountries(), 249) } diff --git a/setup.go b/setup.go index 4db88ff..c84789d 100644 --- a/setup.go +++ b/setup.go @@ -21,7 +21,7 @@ func New() *Query { // NewFromPath creates a Query object from data folder in provided path func NewFromPath(dataPath string) *Query { - if queryInited == false { + queryInitOnce.Do(func() { queryInstance = &Query{ Countries: populateCountries(dataPath), } @@ -45,9 +45,7 @@ func NewFromPath(dataPath string) *Query { } queryInstance.Countries[k] = c } - - queryInited = true - } + }) return queryInstance }