i18n

package module
v2.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2022 License: MIT Imports: 8 Imported by: 0

README

i18n

GitHub tag Build Status codecov Go Report Card GoDoc MIT license

i18n is a minimal, flexible, simple to use and simple to embed (in your own packages) localizations package.
It accept yaml, json or toml for both config and localizations files.

Installation

go get -u github.com/oblq/i18n/v2

Quickstart

Create a new instance:

package main

import (
	"github.com/oblq/i18n/v2"
	"golang.org/x/text/language"
)

func init() {
	// Optionally pass the config file path and nil config.
	// The config file can be in yaml, json or toml format.
	localizer, err := i18n.NewWithConfig(&i18n.Config{
            Locales: []string{
                language.English.String(), // "en"
                language.Italian.String(), // "it"
            },
            Path: "./example/localizations",
        })	
}

Localize a key:

localizer.T("en", "MY_KEY")

Localize a key using plural and multiple parameters:

# ./example/localizations/en.yaml file

WHOAMI: "I'm %s!"
localizer.TP("en", "WHOAMI", "i18n") // -> "I'm i18n!"

Automatically localize a key based on the http request, i18n will first look for the locale by the GetLocaleOverride func, then in cookies (language and/or lang keys), then in Accept-Language header:

func(w http.ResponseWriter, r *http.Request) {
	response := localizer.AutoT(r, "MY_KEY")
	w.WriteHeader(http.StatusOK)
	w.Write([]byte(response))
}

Optionally override the GetLocale func to automatically determine the locale to be used from http requests (using i18n.AutoT func), if an empty string is returned the default methods will be used anyway:

localizer.GetLocaleOverride = func(r *http.Request) string {
    user := MyCustomAuthLib.UserFromRequest(r)
    return user.Locale
}

Localized file server:

localizer.SetFileServer(
    map[string]http.Handler{
        language.English.String(): http.FileServer(http.Dir("./landing_en")),
        language.Italian.String(): http.FileServer(http.Dir("./landing_it")),
    }, 
)

mux.Handle("/", localizer)

Embed i18n in your package:

Use hardcoded localizations, they can be a json, yaml or toml string:

package main

import (
	"github.com/oblq/i18n/v2"
	"golang.org/x/text/language"
)

// keys
const (
	GEM = "GEM" // generic_error_message
)

var hardcodedLocs = map[string]map[string]string{
	language.English.String(): {
		GEM: "Something went wrong, please try again later %s",
	},
	language.Italian.String(): {
		GEM: "Qualcosa è andato storto, riprova più tardi %s",
	},
}

var localizer *i18n.I18n

func init() {
	localizer, err := i18n.NewWithConfig(&i18n.Config{
		Locales: []string{
			language.English.String(), // "en"
			language.Italian.String(), // "it"
		},
		Locs: hardcodedLocs,
	})
}

Middleware

package main

import (
	"net/http"
	
	"github.com/oblq/i18n/v2"
	"golang.org/x/text/language"
)

func init() {
	config := &i18n.Config{
		HTTPLookUpStrategy: []i18n.HTTPLocalePosition{
			{i18n.HTTPLocalePositionIDHeader, "Accept-Language"},
			{i18n.HTTPLocalePositionIDCookie, "locale"},
			{i18n.HTTPLocalePositionIDQuery, "lang"},
		},
		Locales: []string{
			language.Italian.String(), 
			language.English.String(),
		},
	}

	localizer, err := i18n.NewWithConfig(config)
	if err != nil {
		panic(err)
	}

	http.Handle("/this-is-my-locale", localizer.Middleware(http.HandlerFunc(getLocale)))
	http.ListenAndServe(":8080", nil)
}

func getLocale(w http.ResponseWriter, r *http.Request) {
	locale := r.Context().Value(i18n.MiddlewareContextLocaleKey)
	_, _ = w.Write([]byte(locale.(string)))
}

Vendored packages

Author

License

i18n is available under the MIT license. See the LICENSE file for more information.

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

View Source
const MiddlewareContextLocaleKey = "locale"

Variables

View Source
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

func NewWithConfig(config *Config) (*I18n, error)

NewWithConfig create a new instance of i18n.

func NewWithConfigFile

func NewWithConfigFile(configFilePath string) (*I18n, error)

NewWithConfigFile create a new instance of i18n. configFilePath is the path of the config file (like i18n.yaml).

func (*I18n) AutoT

func (i18n *I18n) AutoT(r *http.Request, key string, params ...interface{}) string

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

func (i18n *I18n) AutoTP(r *http.Request, key string, params ...interface{}) string

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

func (i18n *I18n) Configure(configFiles ...string) (err error)

Configure is the github.com/oblq/swap`Configurable` interface implementation.

func (*I18n) GetLanguageTag

func (i18n *I18n) GetLanguageTag(r *http.Request) language.Tag

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

func (i18n *I18n) GetLocale(r *http.Request) (locale string)

GetLocale return GetLanguageTag(r).String() It always returns a valid result.

func (*I18n) LoadLocalizationFiles

func (i18n *I18n) LoadLocalizationFiles(localizationsPath string) (err error)

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

func (i18n *I18n) MatchAvailableLanguageTag(locale string) language.Tag

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

func (i18n *I18n) Middleware(nextHandler http.Handler) http.Handler

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

func (i18n *I18n) New(configFiles ...string) (instance interface{}, err error)

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) ServeHTTP

func (i18n *I18n) ServeHTTP(w http.ResponseWriter, r *http.Request)

func (*I18n) SetFileServer

func (i18n *I18n) SetFileServer(handlers map[string]http.Handler)

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)

func (*I18n) T

func (i18n *I18n) T(locale string, key string, params ...interface{}) string

T translate the key based on the passed locale.

func (*I18n) TP

func (i18n *I18n) TP(locale string, key string, params ...interface{}) string

TP translate the key based on the passed locale and for possibly plural values.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL