Documentation ¶
Overview ¶
Package i18n is a minimal, flexible and simple to use localizations package.
Localization files can be yaml, json or toml.
Get a new instance:
localizer := i18n.NewI18n( "", &i18n.Config{ Locales: []string{"en", "it"}, LocalizationsPath: "./localizations", }, )
Optionally override the GetLocale func, if an empty string is returned the default method will be used anyway:
localizer.GetLocaleOverride = func(r *http.Request) string { user := Auth.UserFromRequest(r) return user.Locale }
Localize a key based on the http request, i18n will first look for user language by the GetLocaleOverride func, then in cookies ("language" and/or "lang" keys), then in 'Accept-Language' header:
localizer.AutoT(r, "MY_KEY")
Localize a key based on the given locale:
localizer.T("en", "MY_KEY")
Optionally pass parameters to be parsed with fmt package:
// en.yaml -> "SAY_HELLO": "Hello, %s!" localizer.T("en", "SAY_HELLO", "Marco")
Optionally use a localized file server:
landingHandler := localizer.FileServer( map[string]http.Handler{ language.English.String(): http.FileServer(http.Dir("./landing_en")), language.Italian.String(): http.FileServer(http.Dir("./landing_ita")), }) mux.Handle("/", landingHandler)
Index ¶
- Constants
- Variables
- type Config
- type HTTPLocalePosition
- type HTTPLocalePositionID
- type I18n
- func (i18n *I18n) AutoT(r *http.Request, key string, params ...interface{}) string
- func (i18n *I18n) AutoTP(r *http.Request, key string, params ...interface{}) string
- func (i18n *I18n) Configure(configFiles ...string) (err error)
- func (i18n *I18n) GetLanguageTag(r *http.Request) language.Tag
- func (i18n *I18n) GetLocale(r *http.Request) (locale string)
- func (i18n *I18n) LoadLocalizationFiles(localizationsPath string) (err error)
- func (i18n *I18n) MatchAvailableLanguageTag(locale string) language.Tag
- func (i18n *I18n) Middleware(nextHandler http.Handler) http.Handler
- func (i18n *I18n) New(configFiles ...string) (instance interface{}, err error)
- func (i18n *I18n) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (i18n *I18n) SetFileServer(handlers map[string]http.Handler)
- func (i18n *I18n) T(locale string, key string, params ...interface{}) string
- func (i18n *I18n) TP(locale string, key string, params ...interface{}) string
Constants ¶
const MiddlewareContextLocaleKey = "locale"
Variables ¶
var DefaultHTTPLookUpStrategy = []HTTPLocalePosition{ {HTTPLocalePositionIDHeader, "Accept-Language"}, {HTTPLocalePositionIDCookie, "lang"}, {HTTPLocalePositionIDQuery, "lang"}, }
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct { // HTTPLookUpStrategy represent the strategy to extract the language from the request. // The order of element is important, the first one is the default. // Default is DefaultMiddlewareLookUpStrategy. HTTPLookUpStrategy []HTTPLocalePosition // Locales order is important, the first one is the default, // they must be ordered from the most preferred to te least one. // A localization file for any given locale must be provided. // Could be easily generated using `language.English.String()` // from `golang.org/x/text/language` package. Locales []string // Path is the path of localization files. // Files will be searched automatically based on Locales. Path string // Locs contains hardcoded localizations. // Use it if you want to use hardcoded localizations, // useful to embed i18n in other library packages. Locs map[string]map[string]string }
Config is the i18n config struct.
The Locales order is important, they must be ordered from the most preferred to te least one, the first one is the default.
Set Path OR Locs, Path takes precedence over Locs. Set Locs if you want to use hardcoded localizations, useful to embed i18n in other library packages. Otherwise, set Path to load localization files.
type HTTPLocalePosition ¶ added in v2.2.0
type HTTPLocalePosition struct { ID HTTPLocalePositionID Key string }
type HTTPLocalePositionID ¶ added in v2.2.0
type HTTPLocalePositionID string
const ( HTTPLocalePositionIDHeader HTTPLocalePositionID = "header" HTTPLocalePositionIDCookie HTTPLocalePositionID = "cookie" HTTPLocalePositionIDQuery HTTPLocalePositionID = "query" )
type I18n ¶
type I18n struct { // Config struct Config *Config // GetLocaleOverride override the default method // to get the http request locale. // If an empty string is returned the default methods // will be used anyway (request's cookies and header). GetLocaleOverride func(r *http.Request) string `json:"-"` // Tags is automatically generated using Config.Locales. // The first one is the default, they must be // ordered from the most preferred to te least one. Tags []language.Tag // contains filtered or unexported fields }
I18n is the i18n instance.
func NewWithConfig ¶
NewWithConfig create a new instance of i18n.
func NewWithConfigFile ¶
NewWithConfigFile create a new instance of i18n. configFilePath is the path of the config file (like i18n.yaml).
func (*I18n) AutoT ¶
AutoT automatically translate the key based on the http request: it will first look for user language by the GetLocaleOverride func, then in cookies ("language" and/or "lang" keys), then in 'Accept-Language' header.
func (*I18n) AutoTP ¶
AutoTP automatically translate the key based on the http request and for possibly plural values: it will first look for user language by the GetLocaleOverride func, then in cookies ("language" and/or "lang" keys), then in 'Accept-Language' header.
func (*I18n) Configure ¶
Configure is the github.com/oblq/swap`Configurable` interface implementation.
func (*I18n) GetLanguageTag ¶
GetLanguageTag return the request language.Tag. A recognized tag is always returned.
<language.Tag>.String() // -> locale
It first looks for the request locale (GetLocale func), then it will look for the corresponding language.Tag in the i18n predefined Tags, if no tag is matched the first one will be returned.
func (*I18n) GetLocale ¶
GetLocale return GetLanguageTag(r).String() It always returns a valid result.
func (*I18n) LoadLocalizationFiles ¶
LoadLocalizationFiles will unmarshal all the matched localization files in i18n.Config.LocalizationsPath for the given i18n.Tags, localization files must be named as the <language.Tag>.String() (locale, e.g.: `en.yml` for `language.English`).
func (*I18n) MatchAvailableLanguageTag ¶ added in v2.3.0
MatchAvailableLanguageTag return one of the available locales corresponding language.Tag.
<language.Tag>.String() // -> locale
A recognized language is always returned. If no locale is matched the first one from the supported list will be returned.
func (*I18n) Middleware ¶ added in v2.2.0
Middleware looks for a language setting in the request and sets the request locale in context. It looks for the language using the `i18n.Config.HTTPLookUpStrategy`.
func (*I18n) New ¶ added in v2.1.0
New is the github.com/oblq/swap`Factory` interface. must be a singleton otherwise a lot of connection to the db will remain open
func (*I18n) SetFileServer ¶
SetFileServer set a different handler for any specific language. The default language will be used if no i18n.Tags tag is matched.
EXAMPLE:
i18nInstance.SetFileServer( map[string]http.Handler{ language.English.String(): http.FileServer(http.Dir("./landing_en")), language.Italian.String(): http.FileServer(http.Dir("./landing_ita")), }) mux.Handle("/", i18nInstance)