From 368c93d38fa24f0eae530d46c4f556b45118caa6 Mon Sep 17 00:00:00 2001 From: Peleus <245629560@qq.com> Date: Tue, 22 Aug 2023 12:57:53 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E9=83=A8=E5=88=86=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E7=BA=BF=E7=A8=8B=E4=B8=8D=E5=AE=89=E5=85=A8=E7=9A=84?= =?UTF-8?q?=20bug=20#180?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- language.go | 13 ++++++++++--- language_test.go | 8 ++++---- 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/language.go b/language.go index 574866c..3c23182 100755 --- a/language.go +++ b/language.go @@ -6,6 +6,7 @@ import ( "fmt" "strconv" "strings" + "sync" ) //go:embed lang @@ -34,6 +35,7 @@ type Language struct { locale string resources map[string]string Error error + rw *sync.RWMutex } // NewLanguage returns a new Language instance. @@ -43,12 +45,16 @@ func NewLanguage() *Language { dir: defaultDir, locale: defaultLocale, resources: make(map[string]string), + rw: new(sync.RWMutex), } } // SetLocale sets language locale. // 设置区域 func (lang *Language) SetLocale(locale string) { + lang.rw.Lock() + defer lang.rw.Unlock() + if len(lang.resources) != 0 { return } @@ -59,14 +65,15 @@ func (lang *Language) SetLocale(locale string) { lang.Error = invalidLocaleError(fileName) return } - if json.Unmarshal(bytes, &lang.resources) != nil { - lang.Error = invalidLocaleError(fileName) - } + _ = json.Unmarshal(bytes, &lang.resources) } // SetResources sets language resources. // 设置资源 func (lang *Language) SetResources(resources map[string]string) { + lang.rw.Lock() + defer lang.rw.Unlock() + if len(lang.resources) == 0 { lang.resources = resources return diff --git a/language_test.go b/language_test.go index d0b4820..31792a7 100755 --- a/language_test.go +++ b/language_test.go @@ -11,8 +11,8 @@ func TestLanguage_SetLocale(t *testing.T) { assert := assert.New(t) tests := []struct { - input1 Carbon // 输入值 - input2 string // 输入值 + input Carbon // 输入值 + locale string // 输入值 expected string // 期望值 }{ {Now(), "en", "1 day after"}, @@ -21,8 +21,8 @@ func TestLanguage_SetLocale(t *testing.T) { for index, test := range tests { lang := NewLanguage() - lang.SetLocale(test.input2) - assert.Equal(test.expected, (test.input1).AddDays(1).SetLanguage(lang).DiffForHumans(test.input1), "Current test index is "+strconv.Itoa(index)) + lang.SetLocale(test.locale) + assert.Equal(test.expected, (test.input).AddDays(1).SetLanguage(lang).DiffForHumans(test.input), "Current test index is "+strconv.Itoa(index)) } }