@@ -35,7 +35,7 @@ type locale struct {
35
35
}
36
36
37
37
type LocaleStore struct {
38
- reloadMu * sync.Mutex // for non-prod(dev), use a mutex for live-reload. for prod, no mutex, no live-reload.
38
+ reloadMu * sync.RWMutex // for non-prod(dev), use a mutex for live-reload. for prod, no mutex, no live-reload.
39
39
40
40
langNames []string
41
41
langDescs []string
@@ -49,7 +49,7 @@ type LocaleStore struct {
49
49
func NewLocaleStore (isProd bool ) * LocaleStore {
50
50
ls := & LocaleStore {localeMap : make (map [string ]* locale ), textIdxMap : make (map [string ]int )}
51
51
if ! isProd {
52
- ls .reloadMu = & sync.Mutex {}
52
+ ls .reloadMu = & sync.RWMutex {}
53
53
}
54
54
return ls
55
55
}
@@ -136,8 +136,8 @@ func (ls *LocaleStore) Tr(lang, trKey string, trArgs ...interface{}) string {
136
136
// Tr translates content to locale language. fall back to default language.
137
137
func (l * locale ) Tr (trKey string , trArgs ... interface {}) string {
138
138
if l .store .reloadMu != nil {
139
- l .store .reloadMu .Lock ()
140
- defer l .store .reloadMu .Unlock ()
139
+ l .store .reloadMu .RLock ()
140
+ defer l .store .reloadMu .RUnlock ()
141
141
}
142
142
msg , _ := l .tryTr (trKey , trArgs ... )
143
143
return msg
@@ -147,6 +147,8 @@ func (l *locale) tryTr(trKey string, trArgs ...interface{}) (msg string, found b
147
147
if l .store .reloadMu != nil {
148
148
now := time .Now ()
149
149
if now .Sub (l .lastReloadCheckTime ) >= time .Second && l .sourceFileInfo != nil && l .sourceFileName != "" {
150
+ l .store .reloadMu .RUnlock () // if the locale file should be reloaded, then we release the read-lock
151
+ l .store .reloadMu .Lock () // and acquire the write-lock
150
152
l .lastReloadCheckTime = now
151
153
if sourceFileInfo , err := os .Stat (l .sourceFileName ); err == nil && ! sourceFileInfo .ModTime ().Equal (l .sourceFileInfo .ModTime ()) {
152
154
if err = l .store .reloadLocaleByIni (l .langName , l .sourceFileName ); err == nil {
@@ -155,6 +157,8 @@ func (l *locale) tryTr(trKey string, trArgs ...interface{}) (msg string, found b
155
157
log .Error ("unable to live-reload the locale file %q, err: %v" , l .sourceFileName , err )
156
158
}
157
159
}
160
+ l .store .reloadMu .Unlock () // release the write-lock
161
+ l .store .reloadMu .RLock () // and re-acquire the read-lock, which was managed by outer Tr function
158
162
}
159
163
}
160
164
trMsg := trKey
0 commit comments