go-i18n

go-i18n is a Go package and a command that helps you translate Go programs into multiple languages.
Versions
- v1 is available at 1.x.x tags.
- v2 is available at 2.x.x tags.
This README always documents the latest version (i.e. v2).
Package i18n 
The i18n package provides support for looking up messages according to a set of locale preferences.
import "github.com/mattermost/go-i18n/v2/i18n"
Create a Bundle to use for the lifetime of your application.
bundle := &i18n.Bundle{DefaultLanguage: language.English}
Load translations into your bundle during initialization.
bundle.LoadMessageFile("en-US.yaml")
Create a Localizer to use for a set of language preferences.
func(w http.ResponseWriter, r *http.Request) {
lang := r.FormValue("lang")
accept := r.Header.Get("Accept-Language")
localizer := i18n.NewLocalizer(bundle, lang, accept)
}
Use the Localizer to lookup messages.
localizer.MustLocalize(&i18n.LocalizeConfig{
DefaultMessage: &i18n.Message{
ID: "PersonCats",
One: "{{.Name}} has {{.Count}} cat.",
Other: "{{.Name}} has {{.Count}} cats.",
},
TemplateData: map[string]interface{}{
"Name": "Nick",
"Count": 2,
},
PluralCount: 2,
}) // Nick has 2 cats.
It requires Go 1.9 or newer.
Command goi18n 
The goi18n command manages message files used by the i18n package.
go get -u github.com/mattermost/go-i18n/v2/goi18n
goi18n -help
Use goi18n extract
to create a message file that contains all the messages defined in your Go source files.
# active.en.toml
[PersonCats]
description = "The number of cats a person has"
one = "{{.Name}} has {{.Count}} cat."
other = "{{.Name}} has {{.Count}} cats."
You can customize the local of your source language with the -sourceLanguage
flag.
Translating a new language
-
Create an empty message file for the language that you want to add (e.g. translate.es.toml
).
-
Run goi18n merge active.en.toml translate.es.toml
to populate translate.es.toml
with the mesages to be translated.
# translate.es.toml
[HelloPerson]
hash = "sha1-5b49bfdad81fedaeefb224b0ffc2acc58b09cff5"
other = "Hello {{.Name}}"
-
After translate.es.toml
has been translated, rename it to active.es.toml
.
# active.es.toml
[HelloPerson]
hash = "sha1-5b49bfdad81fedaeefb224b0ffc2acc58b09cff5"
other = "Hola {{.Name}}"
-
Load active.es.toml
into your bundle.
bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
bundle.LoadMessageFile("active.ar.yaml")
Translating new messages
If you have added new messages to your program:
- Run
goi18n extract
to update active.en.toml
with the new messages.
- Run
goi18n merge active.*.toml
to generate updated translate.*.toml
files.
- Translate all the messages in the
translate.*.toml
files.
- Run
goi18n merge active.*.toml translate.*.toml
to merge the translated messages into the active message files.
License
go-i18n is available under the MIT license. See the LICENSE file for more info.