Skip to content

Commit

Permalink
Merge pull request #32 from bastengao/fix-init-concurrent-race
Browse files Browse the repository at this point in the history
Fix init queryInstance concurrent race
  • Loading branch information
pariz authored Nov 4, 2021
2 parents 1c6a393 + ed3be17 commit d61903d
Show file tree
Hide file tree
Showing 3 changed files with 8 additions and 9 deletions.
9 changes: 5 additions & 4 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
2 changes: 1 addition & 1 deletion query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

}

Expand Down
6 changes: 2 additions & 4 deletions setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
}
Expand All @@ -45,9 +45,7 @@ func NewFromPath(dataPath string) *Query {
}
queryInstance.Countries[k] = c
}

queryInited = true
}
})

return queryInstance
}
Expand Down

0 comments on commit d61903d

Please sign in to comment.