github.com/polarismesh/polaris@v1.17.8/apiserver/httpserver/i18n/translate.go (about) 1 /** 2 * Tencent is pleased to support the open source community by making Polaris available. 3 * 4 * Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. 5 * 6 * Licensed under the BSD 3-Clause License (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * https://opensource.org/licenses/BSD-3-Clause 11 * 12 * Unless required by applicable law or agreed to in writing, software distributed 13 * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 14 * CONDITIONS OF ANY KIND, either express or implied. See the License for the 15 * specific language governing permissions and limitations under the License. 16 */ 17 18 package i18n 19 20 //go:generate go run cmd/gen.go 21 22 import ( 23 "fmt" 24 "sync" 25 26 "github.com/BurntSushi/toml" 27 ii18n "github.com/nicksnyder/go-i18n/v2/i18n" 28 "go.uber.org/zap" 29 "golang.org/x/text/language" 30 31 "github.com/polarismesh/polaris/common/log" 32 "github.com/polarismesh/polaris/common/utils" 33 ) 34 35 var ( 36 bundle *ii18n.Bundle 37 i18nMsgCache map[uint32]*ii18n.Message 38 once sync.Once 39 ) 40 41 func init() { 42 bundle = ii18n.NewBundle(language.English) 43 bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) 44 } 45 46 // LoadI18nMessageFile 加载i18n配置文件 47 func LoadI18nMessageFile(path string) { 48 if _, err := bundle.LoadMessageFile(path); err != nil { 49 log.Error("[i18n][MessageFile] load fail", zap.Error(err)) 50 } 51 } 52 53 // Translate 国际化code所对应的msg信息 54 func Translate(code uint32, langs ...string) (string, error) { 55 once.Do(func() { 56 LoadI18nMessageFile(utils.ConfDir + "i18n/zh.toml") 57 LoadI18nMessageFile(utils.ConfDir + "i18n/en.toml") 58 }) 59 msg, ok := i18nMsgCache[code] 60 if !ok { 61 msg = &ii18n.Message{ID: fmt.Sprintf("%d", code)} 62 } 63 return ii18n.NewLocalizer(bundle, langs...).LocalizeMessage(msg) 64 }