mirror of
https://github.com/TeaOSLab/EdgeCommon.git
synced 2025-11-19 17:10:24 +08:00
部分中文转换为多语言代号
This commit is contained in:
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user