feat: i18n with default lang zh-Hans (translating)

This commit is contained in:
krau
2025-06-08 11:01:33 +08:00
parent 0422c1ac3e
commit c798c7ae99
8 changed files with 213 additions and 64 deletions
+60
View File
@@ -0,0 +1,60 @@
package i18n
import (
"embed"
"maps"
"github.com/krau/SaveAny-Bot/common"
"github.com/nicksnyder/go-i18n/v2/i18n"
"github.com/pelletier/go-toml/v2"
"golang.org/x/text/language"
)
//go:embed locale/*.toml
var localesFS embed.FS
var (
bundle *i18n.Bundle
localizer *i18n.Localizer
)
func Init(lang string) {
bundle = i18n.NewBundle(language.SimplifiedChinese)
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
files, err := localesFS.ReadDir("locale")
if err != nil {
panic("failed to read locale directory: " + err.Error())
}
for _, file := range files {
if _, err := bundle.LoadMessageFileFS(localesFS, "locale/"+file.Name()); err != nil {
panic("failed to load message file: " + err.Error())
}
}
if lang == "" {
lang = "zh-Hans"
}
localizer = i18n.NewLocalizer(bundle, lang)
if localizer == nil {
panic("failed to create localizer, check your config for valid language setting")
}
}
func T(key string, templateData ...map[string]any) string {
if localizer == nil || bundle == nil {
panic("localizer or bundle is not initialized, call Init() first")
}
templateDataMap := make(map[string]any)
for _, data := range templateData {
maps.Copy(templateDataMap, data)
}
msg, err := localizer.Localize(&i18n.LocalizeConfig{
MessageID: key,
TemplateData: templateDataMap,
})
if err != nil {
common.Log.Errorf("failed to localize message for key '%s': %v", key, err)
return key
}
return msg
}
+13
View File
@@ -0,0 +1,13 @@
// Code generated by cmd/gen_i18n. DO NOT EDIT.
package i18nk
const (
CleanCacheFailed = "CleanCacheFailed"
CleaningCache = "CleaningCache"
GetCacheAbsPathFailed = "GetCacheAbsPathFailed"
GetWorkdirFailed = "GetWorkdirFailed"
InvalidCacheDir = "InvalidCacheDir"
Bye = "bye"
Exiting = "exiting"
Initing = "initing"
)
+16
View File
@@ -0,0 +1,16 @@
[initing]
other = "正在启动..."
[exiting]
other = "正在退出..."
[bye]
other = "已退出"
[InvalidCacheDir]
other = "无效的缓存文件夹: {{.Path}}"
[GetWorkdirFailed]
other = "获取工作目录失败: {{.Error}}"
[GetCacheAbsPathFailed]
other = "获取缓存绝对路径失败: {{.Error}}"
[CleaningCache]
other = "正在清理缓存文件夹: {{.Path}}"
[CleanCacheFailed]
other = "清理缓存失败: {{.Error}}"