i18n

The i18n middleware provides internationalization and localization for Flame instances.

You can read source code of this middleware on GitHubopen in new window and API documentation on pkg.go.devopen in new window.

Installation

go get github.com/flamego/i18n

Usage examples

The i18n.I18nopen in new window is used in combination with i18n.Optionsopen in new window to bootstrap the localization engine, which is built upon the shining go-i18n/i18nopen in new window.

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 tagopen in new window, 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
package main

import (
	"github.com/flamego/flamego"
	"github.com/flamego/i18n"
)

func main() {
	f := flamego.Classic()
	f.Use(i18n.I18n(
		i18n.Options{
			Languages: []i18n.Language{
				{Name: "en-US", Description: "English"},
				{Name: "zh-CN", Description: "简体中文"},
			},
		},
	))
	f.Get("/", func(l i18n.Locale) string {
		return l.Translate("greeting")
	})
	f.Run()
}
greeting = How are you?
greeting = 你好吗?

Using the embed.FS

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

import (
	"net/http"

	"github.com/flamego/flamego"
	"github.com/flamego/i18n"

	"main/locales"
)

func main() {
	f := flamego.Classic()
	f.Use(i18n.I18n(
		i18n.Options{
			FileSystem: http.FS(locales.Locales),
			Languages: []i18n.Language{
				{Name: "en-US", Description: "English"},
				{Name: "zh-CN", Description: "简体中文"},
			},
		},
	))
	f.Get("/", func(l i18n.Locale) string {
		return l.Translate("greeting")
	})
	f.Run()
}
package locales

import "embed"

//go:embed *.ini
var Locales embed.FS
greeting = How are you?
greeting = 你好吗?

WARNING

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.