1Panel/backend/i18n/i18n.go

77 lines
1.6 KiB
Go
Raw Normal View History

2022-08-16 23:30:23 +08:00
package i18n
import (
"embed"
2024-02-19 13:55:27 +08:00
"github.com/1Panel-dev/1Panel/backend/global"
2022-08-16 23:30:23 +08:00
"strings"
"github.com/gin-gonic/gin"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
2023-03-11 19:55:37 +08:00
"gopkg.in/yaml.v3"
2022-08-16 23:30:23 +08:00
)
func GetMsgWithMap(key string, maps map[string]interface{}) string {
2024-02-19 13:55:27 +08:00
var content string
2022-08-16 23:30:23 +08:00
if maps == nil {
2024-02-19 13:55:27 +08:00
content, _ = global.I18n.Localize(&i18n.LocalizeConfig{
MessageID: key,
2022-08-16 23:30:23 +08:00
})
} else {
2024-02-19 13:55:27 +08:00
content, _ = global.I18n.Localize(&i18n.LocalizeConfig{
MessageID: key,
2022-08-16 23:30:23 +08:00
TemplateData: maps,
})
}
content = strings.ReplaceAll(content, ": <no value>", "")
if content == "" {
return key
2022-08-16 23:30:23 +08:00
} else {
return content
}
}
func GetErrMsg(key string, maps map[string]interface{}) string {
2024-02-19 13:55:27 +08:00
var content string
if maps == nil {
2024-02-19 13:55:27 +08:00
content, _ = global.I18n.Localize(&i18n.LocalizeConfig{
MessageID: key,
})
} else {
2024-02-19 13:55:27 +08:00
content, _ = global.I18n.Localize(&i18n.LocalizeConfig{
MessageID: key,
TemplateData: maps,
})
}
return content
}
func GetMsgByKey(key string) string {
2024-02-19 13:55:27 +08:00
content, _ := global.I18n.Localize(&i18n.LocalizeConfig{
MessageID: key,
})
return content
}
2022-08-16 23:30:23 +08:00
//go:embed lang/*
var fs embed.FS
2024-02-19 13:55:27 +08:00
var bundle *i18n.Bundle
2022-08-16 23:30:23 +08:00
2024-02-19 13:55:27 +08:00
func UseI18n() gin.HandlerFunc {
return func(context *gin.Context) {
lang := context.GetHeader("Accept-Language")
if lang == "" {
lang = "zh"
}
global.I18n = i18n.NewLocalizer(bundle, lang)
}
}
func Init() {
bundle = i18n.NewBundle(language.Chinese)
bundle.RegisterUnmarshalFunc("yaml", yaml.Unmarshal)
_, _ = bundle.LoadMessageFileFS(fs, "lang/zh.yaml")
_, _ = bundle.LoadMessageFileFS(fs, "lang/en.yaml")
_, _ = bundle.LoadMessageFileFS(fs, "lang/zh-Hant.yaml")
2022-08-16 23:30:23 +08:00
}