2022-08-16 15:30:23 +00:00
|
|
|
package i18n
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
ginI18n "github.com/gin-contrib/i18n"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/nicksnyder/go-i18n/v2/i18n"
|
|
|
|
"golang.org/x/text/language"
|
2023-03-11 11:55:37 +00:00
|
|
|
"gopkg.in/yaml.v3"
|
2022-08-16 15:30:23 +00:00
|
|
|
)
|
|
|
|
|
2023-03-20 02:38:39 +00:00
|
|
|
func GetMsgWithMap(key string, maps map[string]interface{}) string {
|
2022-08-16 15:30:23 +00:00
|
|
|
content := ""
|
|
|
|
if maps == nil {
|
|
|
|
content = ginI18n.MustGetMessage(&i18n.LocalizeConfig{
|
2023-03-20 02:38:39 +00:00
|
|
|
MessageID: key,
|
2022-08-16 15:30:23 +00:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
content = ginI18n.MustGetMessage(&i18n.LocalizeConfig{
|
2023-03-20 02:38:39 +00:00
|
|
|
MessageID: key,
|
2022-08-16 15:30:23 +00:00
|
|
|
TemplateData: maps,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
content = strings.ReplaceAll(content, ": <no value>", "")
|
|
|
|
if content == "" {
|
2023-03-20 02:38:39 +00:00
|
|
|
return key
|
2022-08-16 15:30:23 +00:00
|
|
|
} else {
|
|
|
|
return content
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-20 02:38:39 +00:00
|
|
|
func GetErrMsg(key string, maps map[string]interface{}) string {
|
2022-12-01 07:48:40 +00:00
|
|
|
content := ""
|
|
|
|
if maps == nil {
|
|
|
|
content = ginI18n.MustGetMessage(&i18n.LocalizeConfig{
|
2023-03-20 02:38:39 +00:00
|
|
|
MessageID: key,
|
2022-12-01 07:48:40 +00:00
|
|
|
})
|
|
|
|
} else {
|
|
|
|
content = ginI18n.MustGetMessage(&i18n.LocalizeConfig{
|
2023-03-20 02:38:39 +00:00
|
|
|
MessageID: key,
|
2022-12-01 07:48:40 +00:00
|
|
|
TemplateData: maps,
|
|
|
|
})
|
|
|
|
}
|
|
|
|
return content
|
|
|
|
}
|
|
|
|
|
2022-08-16 15:30:23 +00:00
|
|
|
//go:embed lang/*
|
|
|
|
var fs embed.FS
|
|
|
|
|
|
|
|
func GinI18nLocalize() gin.HandlerFunc {
|
|
|
|
return ginI18n.Localize(
|
|
|
|
ginI18n.WithBundle(&ginI18n.BundleCfg{
|
|
|
|
RootPath: "./lang",
|
|
|
|
AcceptLanguage: []language.Tag{language.Chinese, language.English},
|
|
|
|
DefaultLanguage: language.Chinese,
|
|
|
|
FormatBundleFile: "yaml",
|
|
|
|
UnmarshalFunc: yaml.Unmarshal,
|
|
|
|
Loader: &ginI18n.EmbedLoader{FS: fs},
|
|
|
|
}),
|
|
|
|
ginI18n.WithGetLngHandle(
|
|
|
|
func(context *gin.Context, defaultLng string) string {
|
|
|
|
lng := context.GetHeader("Accept-Language")
|
|
|
|
if lng == "" {
|
|
|
|
return defaultLng
|
|
|
|
}
|
|
|
|
return lng
|
|
|
|
},
|
|
|
|
))
|
|
|
|
}
|