i18n

package
v2.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 11, 2025 License: MIT Imports: 16 Imported by: 7

Documentation

Overview

Package i18n provides internationalization support.

There are two ways to manage translations:

  1. System-wide through i18n.Default() and i18n.SetDefault(): This affects all new components that use i18n.Default()

  2. Instance-level through parser.GetSystemBundle() or parser.ReplaceDefaultBundle(): This affects only a specific parser instance

Note that changing the system bundle via i18n.SetDefault() will not affect existing parser instances that have already been created.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidLanguage                    = errors.New("invalid language in filename")
	ErrDefaultLanguageTranslationsMissing = errors.New("default language translations missing")
	ErrInvalidTranslations                = errors.New("invalid translations")
	ErrEmptyTranslations                  = errors.New("empty translations")
	ErrFailedToSetString                  = errors.New("failed to set string")
	ErrLanguageNotFound                   = errors.New("language not found")
	ErrDefaultLanguageNotFound            = errors.New("default " + ErrLanguageNotFound.Error())
	ErrExtraKey                           = errors.New("extra key")
	ErrMissingKey                         = errors.New("missing key")
	ErrBundleImmutable                    = errors.New("bundle is immutable and cannot be modified")
)

Functions

func GetNativeLanguageName added in v2.3.1

func GetNativeLanguageName(tag language.Tag) string

GetNativeLanguageName returns the native (or first known) name for the given language tag. If no name is found, it returns the BCP 47 string form (e.g., "en").

func GetSystemLocale added in v2.3.1

func GetSystemLocale(getter types.EnvGetter) (language.Tag, error)

GetSystemLocale detects the system locale on Unix-like systems

func IsRTL added in v2.3.1

func IsRTL(tag language.Tag) bool

func LanguageNameToLanguageTag added in v2.3.1

func LanguageNameToLanguageTag(langName string) language.Tag

LanguageNameToLanguageTag maps language display names to language tags. It includes a comprehensive list of languages and their native names, and it can handle region-specific names like "French (Canada)" by stripping the regional information before mapping.

func LanguageTagToLanguageNames added in v2.3.1

func LanguageTagToLanguageNames(tag language.Tag) []string

LanguageTagToLanguageNames returns all known names for a given language tag, including English and native names. It correctly handles regional tags by looking up the base language.

func NormalizeLocaleString added in v2.3.1

func NormalizeLocaleString(locale string) string

NormalizeLocaleString converts various locale string formats into a well-formed BCP-47 language tag. It is designed to clean up locale strings commonly found in environment variables (e.g., "en_US.UTF-8") and produce a canonical representation (e.g., "en-US").

func ParseLanguageTag added in v2.3.1

func ParseLanguageTag(l string) (language.Tag, error)

ParseLanguageTag parses a BCP 47 language tag and returns the corresponding language.Tag object or an error if invalid.

func SetDefault added in v2.1.3

func SetDefault(bundle *Bundle)

func SetDefaultMessageProvider

func SetDefaultMessageProvider(p MessageProvider)

SetDefaultMessageProvider allows users to set their own provider

Types

type Bundle

type Bundle struct {
	// contains filtered or unexported fields
}

func Default

func Default() *Bundle

func DefaultSystemBundle added in v2.3.1

func DefaultSystemBundle() (*Bundle, error)

DefaultSystemBundle creates a new bundle with the built-in translations for en, de, and fr

func NewBundle

func NewBundle() (*Bundle, error)

func NewBundleWithFS

func NewBundleWithFS(fs embed.FS, dirPrefix string, lang ...language.Tag) (*Bundle, error)

func NewEmptyBundle

func NewEmptyBundle() *Bundle

func (*Bundle) AddLanguage

func (b *Bundle) AddLanguage(lang language.Tag, translations map[string]string) error

AddLanguage adds a new language to the bundle or updates existing language if it exists

func (*Bundle) Formatter

func (b *Bundle) Formatter(lang language.Tag) *message.Printer

Formatter returns a printer for the given language

func (*Bundle) GetDefaultLanguage added in v2.1.3

func (b *Bundle) GetDefaultLanguage() language.Tag

func (*Bundle) GetPrinter added in v2.3.1

func (b *Bundle) GetPrinter() *message.Printer

GetPrinter returns a locale-aware printer for the current default language

func (*Bundle) GetTranslations added in v2.3.0

func (b *Bundle) GetTranslations(lang language.Tag) map[string]string

GetTranslations returns all translations for a specific language

func (*Bundle) HasKey

func (b *Bundle) HasKey(lang language.Tag, key string) bool

HasKey checks if a key exists in a language

func (*Bundle) HasLanguage

func (b *Bundle) HasLanguage(lang language.Tag) bool

HasLanguage checks if a language is supported

func (*Bundle) HasTranslations added in v2.3.1

func (b *Bundle) HasTranslations() bool

HasTranslations returns true if the bundle has any translations

func (*Bundle) Languages

func (b *Bundle) Languages() []language.Tag

Languages returns a list of supported languages

func (*Bundle) LanguagesWithKey added in v2.3.1

func (b *Bundle) LanguagesWithKey(key string) []language.Tag

LanguagesWithKey returns languages that have a specific translation key

func (*Bundle) LoadFromFS added in v2.1.3

func (b *Bundle) LoadFromFS(fs embed.FS, dirPrefix string) error

LoadFromFS loads language files from the specified embedded file system directory and updates the bundle's translations. It processes each JSON file to extract translations and associates them with the respective language in the bundle.

func (*Bundle) LoadFromString added in v2.3.1

func (b *Bundle) LoadFromString(lang language.Tag, jsonStr string) error

LoadFromString loads translations from a JSON string for a specific language

func (*Bundle) MatchLanguage added in v2.3.1

func (b *Bundle) MatchLanguage(requested language.Tag) language.Tag

MatchLanguage finds the best matching language from available translations using RFC 4647 language matching. For example: - If user requests "en-CA" and we have "en-US" and "en-GB", it returns one of them - If user requests "en" and we have "en-US", it returns "en-US" - If user requests "de-AT" and we have "de", it returns "de"

func (*Bundle) SetDefaultLanguage

func (b *Bundle) SetDefaultLanguage(lang language.Tag)

SetDefaultLanguage sets the default language, using language matching to find the best available match if the exact language is not available

func (*Bundle) T

func (b *Bundle) T(key string, args ...interface{}) string

T returns the translation for the given key in the default language

func (*Bundle) TL

func (b *Bundle) TL(lang language.Tag, key string, args ...interface{}) string

TL returns the translation for the given language and key

type Formatter added in v2.3.1

type Formatter struct {
	// contains filtered or unexported fields
}

Formatter provides locale-aware formatting for numbers, dates, and times

func NewFormatter added in v2.3.1

func NewFormatter(lang language.Tag) *Formatter

NewFormatter creates a new locale-aware formatter

func (*Formatter) FormatDate added in v2.3.1

func (f *Formatter) FormatDate(t time.Time) string

FormatDate formats a date according to locale rules using the x/text package

func (*Formatter) FormatDateTime added in v2.3.1

func (f *Formatter) FormatDateTime(t time.Time) string

FormatDateTime formats a date and time according to locale rules

func (*Formatter) FormatFloat added in v2.3.1

func (f *Formatter) FormatFloat(n float64, precision int) string

FormatFloat formats a float according to locale rules

func (*Formatter) FormatInt added in v2.3.1

func (f *Formatter) FormatInt(n int) string

FormatInt formats an integer according to locale rules

func (*Formatter) FormatInt64 added in v2.3.1

func (f *Formatter) FormatInt64(n int64) string

FormatInt64 formats an int64 according to locale rules

func (*Formatter) FormatOrdinal added in v2.3.1

func (f *Formatter) FormatOrdinal(n int) string

FormatOrdinal formats an ordinal number (1st, 2nd, etc) according to locale rules

func (*Formatter) FormatPercent added in v2.3.1

func (f *Formatter) FormatPercent(n float64) string

FormatPercent formats a percentage according to locale rules

func (*Formatter) FormatRange added in v2.3.1

func (f *Formatter) FormatRange(min, max interface{}, provider MessageProvider) string

FormatRange formats a numeric range according to locale rules

func (*Formatter) FormatTime added in v2.3.1

func (f *Formatter) FormatTime(t time.Time) string

FormatTime formats a time according to locale rules using the x/text package

type LayeredMessageProvider added in v2.3.0

type LayeredMessageProvider struct {
	// contains filtered or unexported fields
}

LayeredMessageProvider implements MessageProvider with a three-tier lookup system: 1. User bundle (highest priority) 2. System bundle (parser-specific overrides) 3. Default bundle (immutable fallback)

func NewLayeredMessageProvider added in v2.3.0

func NewLayeredMessageProvider(defaultBundle, systemBundle, userBundle *Bundle) *LayeredMessageProvider

NewLayeredMessageProvider creates a new layered message provider

func (*LayeredMessageProvider) FormatFloat added in v2.3.1

func (p *LayeredMessageProvider) FormatFloat(n float64, precision int) string

FormatFloat formats a float according to current locale

func (*LayeredMessageProvider) FormatInt added in v2.3.1

func (p *LayeredMessageProvider) FormatInt(n int) string

FormatInt formats an integer according to current locale

func (*LayeredMessageProvider) FormatRange added in v2.3.1

func (p *LayeredMessageProvider) FormatRange(min, max interface{}) string

FormatRange formats a numeric range according to current locale

func (*LayeredMessageProvider) GetDefaultLanguage added in v2.3.1

func (p *LayeredMessageProvider) GetDefaultLanguage() language.Tag

GetDefaultLanguage returns the current language stored at provider level

func (*LayeredMessageProvider) GetFormattedMessage added in v2.3.0

func (p *LayeredMessageProvider) GetFormattedMessage(key string, args ...interface{}) string

GetFormattedMessage returns the formatted message for the given key with args

func (*LayeredMessageProvider) GetFormatter added in v2.3.1

func (p *LayeredMessageProvider) GetFormatter() *Formatter

GetFormatter returns the current locale-aware formatter

func (*LayeredMessageProvider) GetLanguage added in v2.3.0

func (p *LayeredMessageProvider) GetLanguage() language.Tag

GetLanguage returns the current language stored at provider level

func (*LayeredMessageProvider) GetMessage added in v2.3.0

func (p *LayeredMessageProvider) GetMessage(key string) string

GetMessage returns the message for the given key, checking each layer in order

func (*LayeredMessageProvider) GetPrinter added in v2.3.1

func (p *LayeredMessageProvider) GetPrinter() *message.Printer

GetPrinter returns a locale-aware printer for the current language

func (*LayeredMessageProvider) SetDefaultLanguage added in v2.3.1

func (p *LayeredMessageProvider) SetDefaultLanguage(lang language.Tag)

SetDefaultLanguage sets the current language for the provider, using language matching to find the best available match

func (*LayeredMessageProvider) SetSystemBundle added in v2.3.0

func (p *LayeredMessageProvider) SetSystemBundle(bundle *Bundle)

SetSystemBundle updates the system bundle

func (*LayeredMessageProvider) SetUserBundle added in v2.3.0

func (p *LayeredMessageProvider) SetUserBundle(bundle *Bundle)

SetUserBundle updates the user bundle

func (*LayeredMessageProvider) T added in v2.3.1

func (p *LayeredMessageProvider) T(key string, args ...interface{}) string

T returns the translation for the given key in the current language

func (*LayeredMessageProvider) TL added in v2.3.1

func (p *LayeredMessageProvider) TL(lang language.Tag, key string, args ...interface{}) string

TL returns the translation for the given language and key

type Locale added in v2.3.1

type Locale struct {
	Tag          language.Tag
	Translations string
}

Locale represents a system locale with its translations

func NewLocale added in v2.3.1

func NewLocale(tag language.Tag, translations string) Locale

NewLocale creates a new system locale

type MessageProvider

type MessageProvider interface {
	GetMessage(key string) string
}

MessageProvider defines an interface for getting default messages

type TrError

type TrError struct {
	// contains filtered or unexported fields
}

TrError represents a translatable error with optional formatting arguments and error wrapping support. It implements both the TranslatableError interface and the standard error interface.

Example usage:

err := NewError("validation.error")
err = err.WithArgs("field", "value")
err = err.Wrap(originalError)

func NewError

func NewError(key string) *TrError

NewError creates a new translatable error with a key

func NewErrorWithProvider added in v2.3.0

func NewErrorWithProvider(key string, provider MessageProvider) *TrError

NewErrorWithProvider creates a new translatable error with a key and specific provider

func (*TrError) Args

func (e *TrError) Args() []interface{}

Args returns the format arguments

func (*TrError) Error

func (e *TrError) Error() string

Error returns the default message, formatted with args if provided

func (*TrError) Format added in v2.3.0

func (e *TrError) Format(provider MessageProvider) string

func (*TrError) Is

func (e *TrError) Is(target error) bool

Is implements errors.Is for comparison with the sentinel error

func (*TrError) Key

func (e *TrError) Key() string

Key returns the translation key

func (*TrError) Unwrap

func (e *TrError) Unwrap() error

Unwrap returns the wrapped error

func (*TrError) WithArgs

func (e *TrError) WithArgs(args ...interface{}) TranslatableError

WithArgs returns a copy of the error with format arguments

func (*TrError) Wrap

func (e *TrError) Wrap(err error) TranslatableError

Wrap returns a new error that wraps another error

type Translatable added in v2.3.0

type Translatable interface {
	T(provider MessageProvider) string
}

type TranslatableError

type TranslatableError interface {
	error
	Key() string
	Args() []interface{}
	Unwrap() error
	WithArgs(args ...interface{}) TranslatableError
	Wrap(err error) TranslatableError
	Is(target error) bool
	Format(provider MessageProvider) string
}

TranslatableError represents an error that can be translated

type TranslatableMessage added in v2.3.0

type TranslatableMessage struct {
	MsgOrKey string
}

func NewTranslatable added in v2.3.0

func NewTranslatable(msgOrKey string) *TranslatableMessage

func (*TranslatableMessage) T added in v2.3.0

type Translator added in v2.1.3

type Translator interface {
	T(key string, args ...interface{}) string
	TL(lang language.Tag, key string, args ...interface{}) string
	SetDefaultLanguage(lang language.Tag)
	GetDefaultLanguage() language.Tag
	GetPrinter() *message.Printer
}

Translator is an interface for handling internationalization and localization of strings in an application. T retrieves a localized string based on a key and optional arguments for formatting. TL retrieves a localized string based on language, key and optional arguments for formatting. SetDefaultLanguage sets the default language for translation operations. GetDefaultLanguage retrieves the default language currently set for translation. GetPrinter returns a locale-aware printer for standard Go formatting patterns (%d, %f, %s, etc.)

Directories

Path Synopsis
locales
ar
de
en
es
fr
he
hi
ja
pt
zh

Jump to

Keyboard shortcuts

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