Skip to content

i18n

The i18n middleware provides internationalization and localization for Flame instances.

You can read source code of this middleware on GitHub and API documentation on pkg.go.dev.

Installation

go get github.com/flamego/i18n

Usage examples

The i18n.I18n is used in combination with i18n.Options to bootstrap the localization engine, which is built upon the shining go-i18n/i18n.

By default, the locale files should resides in the “locales” directory and be named in the format of locale_%s.ini, where %s is the IETF BCP 47 language tag, e.g. “en-US”, “zh-CN”.

Using local files

$ tree .
.
├── locales
│   ├── locale_en-US.ini
│   └── locale_zh-CN.ini
├── go.mod
├── go.sum
└── main.go

Using the embed.FS

$ tree .
.
├── locales
│   ├── embed.go
│   ├── locale_en-US.ini
│   └── locale_zh-CN.ini
├── go.mod
├── go.sum
└── main.go
Because the Go embed encodes the entire path (i.e. including parent directories), the embedding should happen within the same directory as locale files.

Determine the language

The i18n middleware uses following technique to determine which language to use for translation:

  1. Look at the URL query parameter, by default it is lang, e.g. lang=en-US would force translation in “English (Unitied Stats)”.
  2. Look at the cookie value, by default it’s the value of lang.
  3. Look at the Accept-Language request header.
  4. Finally, fall back to the default language, which by default is the first language specified as the i18n.Options.Languages.

Regardless of how the language was determined, the cookie value is updated for saving preference.