修复部分方法线程不安全的 bug #180

This commit is contained in:
Peleus 2023-08-22 12:57:53 +08:00
parent 74f046dcf2
commit 368c93d38f
2 changed files with 14 additions and 7 deletions

View File

@ -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

View File

@ -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))
}
}