If you want to use go-i18n in your project, you first have to make one or more translation maps. There are several formats supported.
All .json
and .js
files loaded with the NewTemplateFile
loader are interpreted as a flat list of key-value pairs. Nested items are allowed and will be concatenated with a dot.
For example:
{
"foo": {
"bar": {
"testing"
}
}
}
Here, foo → bar
is accessible as foo.bar
translation key.
All .yml
and .yaml
files loaded with the NewTemplateFile
loader are
interpreted as Rails Application compatible language files, see the Rails
Internationalization page for more details.
A basic project structure may look like follows:
package app
import (
"git.maze.io/maze/go-i18n"
"golang.org/net/http"
"golang.org/x/text/language"
)
func main() {
var lang = i18n.New(language.English)
lang.Add(i18n.NewMap(language.English, map[string]string{
"hello %s": "Hello %s!",
}))
lang.Add(i18n.NewMap(language.Dutch, map[string]string{
"hello %s": "Hallo %s!",
}))
lang.Add(i18n.NewMap(language.SimplifiedChinese, map[string]string{
"hello %s": "%s 你好!",
}))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t := lang.Accept(r.Header().Get("Accept-Language"))
t.Fprintf(w, "hello %s", r.RemoteAddr)
})
http.ListenAndServe(":8000", nil)
}
You can use i18n with many web frameworks, some of which are documented below.
Beego integration
Add these three lines before "beego.Run()" in your main() function.
for k, fn := range lang.TemplateFuncs() {
beego.AddFuncMap(k, fn)
}
Revel integration
package app
import (
"git.maze.io/maze/go-i18n"
"github.com/revel/revel"
"golang.org/x/text/language"
)
var lang *i18n.I18N
func init() {
var err error
if lang, err = i18n.New(language.English); err != nil {
panic(err)
}
lang.TemplateInject(revel.TemplateFuncs)
}
Pongo2 integration
package app
import (
"git.maze.io/maze/go-i18n"
"github.com/flosch/pongo2"
"golang.org/x/text/language"
)
var lang *i18n.I18N
func init() {
var err error
if lang, err = i18n.New(language.English); err != nil {
panic(err)
}
pongo2.RegisterFilter("translate",
func(in *pongo2.Value, param *pongo2.Value) (out *pongo2.Value, err *pongo2.Error) {
if param != nil {
return pongo2.AsValue(lang.Translate(param.String(), in.String())), nil
}
return pongo2.AsValue(lang.Translate(lang.Default().String(), in.String())), nil
},
)
}