feat: 缓存处理国际化数据

This commit is contained in:
TsMask
2023-11-10 18:09:05 +08:00
parent cc93ff9842
commit 30f1776fe7
2 changed files with 75 additions and 0 deletions

View File

@@ -0,0 +1,73 @@
package i18n
import (
"fmt"
"regexp"
systemService "ems.agt/src/modules/system/service"
)
// localeItem 国际化数据项
type localeItem struct {
Key string `json:"key"`
Value string `json:"value"`
}
// localeMap 国际化数据组
var localeMap = make(map[string][]localeItem)
// ClearLocaleData 清空国际化数据
func ClearLocaleData() {
localeMap = make(map[string][]localeItem)
}
// LoadLocaleData 加载国际化数据
func LoadLocaleData(language string) []localeItem {
dictType := fmt.Sprintf("i18n_%s", language)
dictTypeList := systemService.NewSysDictTypeImpl.DictDataCache(dictType)
localeData := []localeItem{}
for _, v := range dictTypeList {
localeData = append(localeData, localeItem{
Key: v.DictLabel,
Value: v.DictValue,
})
}
localeMap[language] = localeData
return localeData
}
// TKey 翻译键
func TKey(language, key string) string {
value := key
if key == "" {
return value
}
arr, ok := localeMap[language]
if !ok || len(arr) == 0 {
arr = LoadLocaleData(language)
}
for _, v := range arr {
if v.Key == key {
value = v.Value
break
}
}
return value
}
// TTemplate 翻译模板字符串
func TTemplate(language, key string, params map[string]any) string {
templateString := TKey(language, key)
re := regexp.MustCompile("{(.*?)}")
result := re.ReplaceAllStringFunc(templateString, func(match string) string {
key := match[1 : len(match)-1]
if val, ok := params[key]; ok {
return fmt.Sprint(val)
}
return match
})
return result
}

View File

@@ -7,6 +7,7 @@ import (
"time"
"ems.agt/src/framework/constants/common"
"ems.agt/src/framework/i18n"
"ems.agt/src/framework/utils/ctx"
"ems.agt/src/framework/utils/file"
"ems.agt/src/framework/utils/parse"
@@ -171,6 +172,7 @@ func (s *SysDictTypeController) Remove(c *gin.Context) {
// PUT /refreshCache
func (s *SysDictTypeController) RefreshCache(c *gin.Context) {
s.sysDictTypeService.ResetDictCache()
i18n.ClearLocaleData() // 清空国际化数据
c.JSON(200, result.Ok(nil))
}