部分中文转换为多语言代号

This commit is contained in:
刘祥超
2023-06-28 16:19:05 +08:00
parent bd57d35d63
commit 9db82b0bea
18 changed files with 656 additions and 164 deletions

View File

@@ -2,6 +2,16 @@
package langs
import (
"errors"
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"strings"
)
const varPrefix = "lang."
type LangCode = string
type Lang struct {
code string
@@ -30,3 +40,39 @@ func (this *Lang) Get(messageCode string) string {
func (this *Lang) GetAll() map[string]string {
return this.messageMap
}
// Compile variable to literal strings
func (this *Lang) Compile() error {
for code, oldMessage := range this.messageMap {
message, err := this.get(code, 0)
if err != nil {
return errors.New("compile '" + code + "': '" + oldMessage + "' failed: " + err.Error())
}
this.messageMap[code] = message
}
return nil
}
func (this *Lang) get(messageCode string, loopIndex int) (string, error) {
if loopIndex >= 8 /** max recurse **/ {
return "", errors.New("too many recurse")
}
loopIndex++
message, ok := this.messageMap[messageCode]
if len(message) == 0 {
if !ok && loopIndex > 1 {
// recover as variable
return "${" + varPrefix + messageCode + "}", errors.New("can not find message for code '" + messageCode + "'")
}
return "", nil
}
return configutils.ParseVariablesError(message, func(varName string) (value string, err error) {
if !strings.HasPrefix(varName, varPrefix) {
return "${" + varName + "}", nil
}
return this.get(varName[len(varPrefix):], loopIndex)
})
}