@@ -35,7 +35,7 @@ type locale struct {
3535}
3636
3737type 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.
3939
4040 langNames []string
4141 langDescs []string
@@ -49,7 +49,7 @@ type LocaleStore struct {
4949func NewLocaleStore (isProd bool ) * LocaleStore {
5050 ls := & LocaleStore {localeMap : make (map [string ]* locale ), textIdxMap : make (map [string ]int )}
5151 if ! isProd {
52- ls .reloadMu = & sync.Mutex {}
52+ ls .reloadMu = & sync.RWMutex {}
5353 }
5454 return ls
5555}
@@ -136,8 +136,8 @@ func (ls *LocaleStore) Tr(lang, trKey string, trArgs ...interface{}) string {
136136// Tr translates content to locale language. fall back to default language.
137137func (l * locale ) Tr (trKey string , trArgs ... interface {}) string {
138138 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 ()
141141 }
142142 msg , _ := l .tryTr (trKey , trArgs ... )
143143 return msg
@@ -147,6 +147,8 @@ func (l *locale) tryTr(trKey string, trArgs ...interface{}) (msg string, found b
147147 if l .store .reloadMu != nil {
148148 now := time .Now ()
149149 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
150152 l .lastReloadCheckTime = now
151153 if sourceFileInfo , err := os .Stat (l .sourceFileName ); err == nil && ! sourceFileInfo .ModTime ().Equal (l .sourceFileInfo .ModTime ()) {
152154 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
155157 log .Error ("unable to live-reload the locale file %q, err: %v" , l .sourceFileName , err )
156158 }
157159 }
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
158162 }
159163 }
160164 trMsg := trKey
0 commit comments