I18next Go

Sample:
import (
"fmt"
"net/http"
i18next "codeberg.org/lil5/i18next_go"
)
func main() {
i18n := i18next.Init(i18next.Options{
Languages: []string{"en", "de"},
FallbackLng: "en",
Ns: []string{"translation"},
DefaultNs: "translation",
Resources: map[string]map[string]map[string]string{
"en": {
"translation": {
"helloWorld": "Hello world, this is translated using: {{product}}!",
},
},
"de": {
"translation": {
"helloWorld": "Hallo Welt, dies wird übersetzt mit: {{product}}!",
},
},
},
})
mux := http.NewServeMux()
mux.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
t := i18n.GetContextWithLanguageDetect(r, nil)
w.Header().Set("Content-Type", "text/html;charset=UTF-8")
w.WriteHeader(http.StatusOK)
fmt.Fprint(w, t.T("helloWorld", map[string]any{"product": "i18next"}))
})
http.ListenAndServe("localhost:8090", mux)
}
Getting started
- Create a
i18n variable.
i18n := i18next.Init(i18next.Options{
Languages: []string{"en", "de"},
FallbackLng: "en",
Ns: []string{"translation"},
// // Add translations in code (optional)
// Resources: map[string]map[string]map[string]string{
// "en": { "translation": { "lorem": "Lorem" } },
// "de": { "translation": { "lorem": "Lörem" } },
// }
})
-
Add translations from json files (optional)
First embed the files into the binary, then use {{lng}} and {{ns}} to denote the language and namespace respectively.
//go:embed locales
var localesFS embed.FS
i18n.AddLocaleFS(localesFS, "locales/{{lng}}/{{ns}}.json")
// This would load the following files:
// -> locales/en/translation.json
// -> locales/de/translation.json
-
Create a t variable
I a request handler like in mux.HandleFunc use the request to find a requested language.
t := i18n.GetContextWithLanguageDetect(r, nil)
// Or if you know which language to use:
t := i18n.GetContext("de")
- Translate with keys
t.T("lorem")
// -> Lörem
Interpolation
Basic translations t.T
// { "hello": "Hallo" }
t.T("hello")
// -> Hallo
// { "dearName": "Lieber {{name}}" }
t.T("dearName", map[string]any{"name":"John"})
// -> Lieber John
// { "day_one": "ein Tag", "day_other": "{{count}} Tage" }
t.T("day", map[string]any{"count":1})
// -> ein Tag
t.T("day", map[string]any{"count":2})
// -> 2 Tage
Support for setting namespace is available as well
// "de": {
// "translation": { "hello": "Hallo" },
// "errPage": { "experiencingTechDiff": "Wir haben derzeit technische Schwierigkeiten." },
t.T("experiencingTechDiff", map[string]any{"ns": "errPage"})
// -> Wir haben derzeit technische Schwierigkeiten.
Element replacements t.Trans
// { "pleaseClick<0>Here</0>": "Bitte klicken Sie <0>hier</0>" }
t.Trans("pleaseClick<0>Here</0>", map[string]any{
"0": func (s string) string {
return `<a href="#">`+s+"</a>"
}
})
// -> Bitte klicken Sie <a href="#">hier</a>
License
MIT License