mirror of
https://gitee.com/dromara/carbon.git
synced 2024-11-29 18:57:37 +08:00
修复部分方法线程不安全的 bug #180
This commit is contained in:
parent
74f046dcf2
commit
368c93d38f
13
language.go
13
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
|
||||
|
@ -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))
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user