1
0
mirror of https://github.com/astaxie/beego.git synced 2024-12-23 17:20:50 +00:00
Beego/middleware/i18n.go

60 lines
1.3 KiB
Go
Raw Normal View History

2014-04-12 05:18:18 +00:00
// Beego (http://beego.me/)
2014-07-03 15:40:21 +00:00
//
2014-04-12 05:18:18 +00:00
// @description beego is an open-source, high-performance web framework for the Go programming language.
2014-07-03 15:40:21 +00:00
//
2014-04-12 05:18:18 +00:00
// @link http://github.com/astaxie/beego for the canonical source repository
2014-07-03 15:40:21 +00:00
//
2014-04-12 05:18:18 +00:00
// @license http://github.com/astaxie/beego/blob/master/LICENSE
2014-07-03 15:40:21 +00:00
//
2014-04-12 05:18:18 +00:00
// @authors astaxie
package middleware
2014-06-27 09:53:53 +00:00
import (
"encoding/json"
"io/ioutil"
"os"
)
type Translation struct {
filepath string
CurrentLocal string
Locales map[string]map[string]string
}
func NewLocale(filepath string, defaultlocal string) *Translation {
i18n := make(map[string]map[string]string)
file, err := os.Open(filepath)
if err != nil {
panic("open " + filepath + " err :" + err.Error())
}
data, err := ioutil.ReadAll(file)
if err != nil {
panic("read " + filepath + " err :" + err.Error())
}
err = json.Unmarshal(data, &i18n)
if err != nil {
panic("json.Unmarshal " + filepath + " err :" + err.Error())
}
return &Translation{
filepath: filepath,
CurrentLocal: defaultlocal,
Locales: i18n,
}
}
func (t *Translation) SetLocale(local string) {
t.CurrentLocal = local
}
func (t *Translation) Translate(key string, local string) string {
if local == "" {
local = t.CurrentLocal
}
if ct, ok := t.Locales[key]; ok {
if v, o := ct[local]; o {
return v
}
}
return key
}