2014-09-12 13:10:58 +04:00
|
|
|
// 国际化操作.
|
2014-08-25 18:17:02 +04:00
|
|
|
package i18n
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2014-10-28 09:38:27 +03:00
|
|
|
"strings"
|
2014-09-08 07:37:34 +04:00
|
|
|
|
|
|
|
"github.com/golang/glog"
|
2014-08-25 18:17:02 +04:00
|
|
|
)
|
|
|
|
|
|
|
|
type locale struct {
|
|
|
|
Name string
|
|
|
|
Langs map[string]interface{}
|
|
|
|
TimeZone string
|
|
|
|
}
|
|
|
|
|
|
|
|
// 所有的 locales.
|
|
|
|
var Locales = map[string]locale{}
|
|
|
|
|
2014-09-12 13:10:58 +04:00
|
|
|
// 加载国际化配置.
|
2014-09-02 18:57:30 +04:00
|
|
|
func Load() {
|
2014-10-28 09:38:27 +03:00
|
|
|
f, _ := os.Open("i18n")
|
|
|
|
names, _ := f.Readdirnames(-1)
|
|
|
|
f.Close()
|
2014-08-25 18:17:02 +04:00
|
|
|
|
2014-10-28 09:38:27 +03:00
|
|
|
for _, name := range names {
|
|
|
|
if !strings.HasSuffix(name, ".json") {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
loc := name[:strings.LastIndex(name, ".")]
|
|
|
|
load(loc)
|
|
|
|
}
|
2014-10-23 17:43:35 +04:00
|
|
|
}
|
|
|
|
|
|
|
|
func load(localeStr string) {
|
|
|
|
bytes, err := ioutil.ReadFile("i18n/" + localeStr + ".json")
|
|
|
|
if nil != err {
|
|
|
|
glog.Error(err)
|
|
|
|
|
|
|
|
os.Exit(-1)
|
|
|
|
}
|
2014-08-25 18:17:02 +04:00
|
|
|
|
2014-10-23 17:43:35 +04:00
|
|
|
l := locale{Name: localeStr}
|
2014-08-25 18:17:02 +04:00
|
|
|
|
2014-10-23 17:43:35 +04:00
|
|
|
err = json.Unmarshal(bytes, &l.Langs)
|
|
|
|
if nil != err {
|
2014-08-25 18:17:02 +04:00
|
|
|
glog.Error(err)
|
|
|
|
|
|
|
|
os.Exit(-1)
|
|
|
|
}
|
|
|
|
|
2014-10-23 17:43:35 +04:00
|
|
|
Locales[localeStr] = l
|
2014-08-25 18:17:02 +04:00
|
|
|
|
2014-10-23 17:43:35 +04:00
|
|
|
glog.V(5).Infof("Loaded [%s] locale configuration", localeStr)
|
|
|
|
}
|
2014-09-16 07:36:21 +04:00
|
|
|
|
2014-10-23 17:43:35 +04:00
|
|
|
// 获取语言配置项.
|
|
|
|
func Get(locale, key string) interface{} {
|
2014-09-16 07:36:21 +04:00
|
|
|
return Locales[locale].Langs[key]
|
|
|
|
}
|
|
|
|
|
2014-10-23 17:43:35 +04:00
|
|
|
// 获取语言配置.
|
|
|
|
func GetAll(locale string) map[string]interface{} {
|
2014-08-25 18:17:02 +04:00
|
|
|
return Locales[locale].Langs
|
|
|
|
}
|