i18n is a simple internationalization library for Golang. It provides a way to translate strings into multiple languages. This library is wrapper for go-i18n with some additional features.
go get -u github.com/ahmadfaizk/i18n
- Support translation file in YAML, JSON, and TOML format
- Translation
- Context translation
- Parametrized translation
- Missing translation Fallback
- Custom extract language from Context
# locales/en.yaml
hello: Hello
hello_name: Hello, {{.name}}
hello_name_age: Hello, {{.name}}. You are {{.age}} years old
# locales/id.yaml
hello: Halo
hello_name: Halo, {{.name}}
hello_name_age: Halo, {{.name}}. Kamu berumur {{.age}} tahun
import (
"github.com/ahmadfaizk/i18n"
"golang.org/x/text/language"
"gopkg.in/yaml.v3"
)
i18n.Init(language.English,
i18n.WithUnmarshalFunc("yaml", yaml.Unmarshal),
i18n.WithTranslationFile("locales/en.yaml", "locales/id.yaml"),
)
fmt.Println(i18n.T("hello"))
// Hello
fmt.Println(i18n.T("hello", i18n.Lang("id")))
// Halo
fmt.Println(i18n.T("hello_name", i18n.Param("name", "John")))
// Hello, John
fmt.Println(i18n.T("hello_name", i18n.Lang("id"), i18n.Param("name", "John")))
// Halo, John
fmt.Println(i18n.T("hello_name_age", i18n.Params{"name": "John", "age": 20}))
// Hello, John. You are 20 years old
fmt.Println(i18n.T("hello_name_age", i18n.Lang("id"), i18n.Params{"name": "John", "age": 20}))
// Halo, John. Kamu berumur 20 tahun
See examples/ for a variety of examples.
package main
import (
"github.com/ahmadfaizk/i18n"
"github.com/go-chi/chi/v5"
"golang.org/x/text/language"
"gopkg.in/yaml.v3"
"net/http"
)
func main() {
if err := i18n.Init(language.English,
i18n.WithUnmarshalFunc("yaml", yaml.Unmarshal),
i18n.WithTranslationFile("locales/en.yaml", "locales/id.yaml"),
); err != nil {
panic(err)
}
r := chi.NewRouter()
r.Use(i18n.Middleware)
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
message := i18n.TCtx(r.Context(), "hello")
_, _ = w.Write([]byte(message))
})
r.Get("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "name")
message := i18n.TCtx(r.Context(), "hello_name", i18n.Params{"name": name})
_, _ = w.Write([]byte(message))
})
if err := http.ListenAndServe(":3000", r); err != nil {
panic(err)
}
}
curl http://localhost:3000/hello # Hello
curl http://localhost:3000/hello/John # Hello, John
curl -H "Accept-Language: id" http://localhost:3000/hello # Halo
curl -H "Accept-Language: id" http://localhost:3000/hello/John # Halo, John
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
This project is licensed under the MIT License - see the LICENSE file for details