i18n

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 13, 2019 License: MIT Imports: 14 Imported by: 0

README

i18n

GitHub tag Build Status codecov Go Report Card GoDoc MIT license sprbox

i18n is a minimal, flexible, simple to use and simple to embed (in your packages) localizations package.
It support yaml, json or toml localization files.

i18n is ready to be used in sprbox.

Install

$ go get github.com/oblq/i18n

Quickstart

Get a new instance:

package main

import (
	"github.com/oblq/i18n"
	"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 := i18n.New(
        "",
        &i18n.Config{
            Locales: []string{
                language.English.String(), // "en"
                language.Italian.String(), // "it"
            },
            Path: "./example/localizations",
        },
    )	
}

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 method will be used anyway:

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

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

Localize a key:

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

Optionally pass parameters to be parsed with fmt package, given the en.yaml localization file:

"SAY_HELLO": 
    one: "Hello, %s!"
    other: "Hello, %s and %s!"

...localize a key using plural and multiple parameters:

localizer.TP("en", true, "SAY_HELLO", "Marco", "Valentina") // -> "Hello, Marco and Valentina!"

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_ita")),
    }, 
)

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"
	"golang.org/x/text/language"
)

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

var hardcodedLocs = map[string]map[string]i18n.Localization{
	language.English.String(): {
		GEM: {
			One:   "Something went wrong, please try again later %s",
			Other: "Some things went wrong, please try again later %s",
		},
	},
	language.Italian.String(): {
		GEM: {
			One:   "Qualcosa è andato storto, riprova più tardi %s",
			Other: "Alcune cose sono andate storte, riprova più tardi %s",
		},
	},
}

var localizer *i18n.I18n

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

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

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Config

type Config struct {
	// 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.
	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]*Localization
}

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 I18n

type I18n struct {
	// Config struct
	Config *Config

	// GetLocaleOverride override the default method
	// to get the http request locale.
	// If nothing is returned the default method will be
	// called 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

New create a new instance of i18n.

func NewWithConfigFile

func NewWithConfigFile(configFilePath string) *I18n

New 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, plural bool, 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) 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 look 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 return 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, eg.: `en.yml` for `language.English`).

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

func (i18n *I18n) SpareConfig(configFiles []string) (err error)

SpareConfig is the sprbox 'configurable' interface implementation.

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, plural bool, key string, params ...interface{}) string

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

type Localization

type Localization struct {
	One, Other string
}

Localization represent a key value with localized strings for both single and plural results

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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