Documentation
¶
Index ¶
- Variables
- func CultureHelpers(service CultureService, localeKey string) map[string]any
- func FormatCurrency(locale string, amount float64, currency string) string
- func FormatDate(locale string, t time.Time) string
- func FormatDateTime(locale string, t time.Time) string
- func FormatList(locale string, items []string) string
- func FormatMeasurement(locale string, value float64, unit string) string
- func FormatNumber(locale string, value float64, decimals int) string
- func FormatOrdinal(locale string, value int) string
- func FormatPercent(locale string, value float64, decimals int) string
- func FormatPhone(locale, raw string) string
- func FormatTime(locale string, t time.Time) string
- func GeneratedCLDRLocales() []string
- func LocaleParent(locale string) string
- func LocaleParentChain(locale string) []string
- func NormalizeAndSortLocales(locales []string) []string
- func NormalizeLocale(locale string) string
- func NormalizeLocales(locales []string) []string
- func RegisterCLDRFormatters(registry *FormatterRegistry, locales ...string)
- func RegisterGeneratedCLDRFormatters(registry *FormatterRegistry)
- func RegisterPhoneDialPlan(locale string, plan PhoneDialPlan)
- func RegisterPhoneFormatter(locale string, formatter PhoneFormatterFunc)
- func RegisterXTextFormatters(registry *FormatterRegistry, rulesProvider *FormattingRulesProvider, ...)
- func TemplateHelpers(t Translator, cfg HelperConfig) map[string]any
- type Config
- func (cfg *Config) BuildTranslator() (Translator, error)
- func (cfg *Config) CultureService() CultureService
- func (cfg *Config) FormatterRegistry() *FormatterRegistry
- func (cfg *Config) LocaleCatalog() *LocaleCatalog
- func (cfg *Config) TemplateHelpers(t Translator, helperCfg HelperConfig) map[string]any
- type CultureData
- type CultureDataLoader
- type CultureService
- type CurrencyFormatRules
- type CurrencyInfo
- type DatePatternRules
- type FallbackResolver
- type FileLoader
- type Formatter
- type FormatterCapabilities
- type FormatterFunc
- type FormatterProvider
- type FormatterRegistry
- func (r *FormatterRegistry) Formatter(name, locale string) (any, bool)
- func (r *FormatterRegistry) FuncMap(locale string) map[string]any
- func (r *FormatterRegistry) Register(name string, fn any)
- func (r *FormatterRegistry) RegisterLocale(locale, name string, fn any)
- func (r *FormatterRegistry) RegisterProvider(locale string, provider FormatterProvider)
- func (r *FormatterRegistry) RegisterTypedProvider(locale string, provider TypedFormatterProvider)
- type FormatterRegistryOption
- func WithFormatterRegistryLocales(locales ...string) FormatterRegistryOption
- func WithFormatterRegistryProvider(locale string, provider FormatterProvider) FormatterRegistryOption
- func WithFormatterRegistryResolver(resolver FallbackResolver) FormatterRegistryOption
- func WithFormatterRegistryTypedProvider(locale string, provider TypedFormatterProvider) FormatterRegistryOption
- func WithFormattingRulesProvider(provider *FormattingRulesProvider) FormatterRegistryOption
- type FormattingDataLoader
- type FormattingRules
- type FormattingRulesProvider
- type HelperConfig
- type HookedTranslator
- type Loader
- type LoaderFunc
- type Locale
- type LocaleCatalog
- func (c *LocaleCatalog) ActiveLocaleCodes() []string
- func (c *LocaleCatalog) AllLocaleCodes() []string
- func (c *LocaleCatalog) DecodeMetadata(locale string, out any) error
- func (c *LocaleCatalog) DefaultLocale() string
- func (c *LocaleCatalog) DisplayName(locale string) string
- func (c *LocaleCatalog) Fallbacks(locale string) []string
- func (c *LocaleCatalog) Has(locale string) bool
- func (c *LocaleCatalog) IsActive(locale string) bool
- func (c *LocaleCatalog) Locale(locale string) (LocaleMetadata, bool)
- func (c *LocaleCatalog) Match(locale string) (LocaleMetadata, bool)
- func (c *LocaleCatalog) MatchAcceptLanguage(header string) (LocaleMetadata, bool)
- func (c *LocaleCatalog) MatchAcceptLanguageWithOptions(header string, opts MatchOptions) (LocaleMetadata, bool)
- func (c *LocaleCatalog) Metadata(locale string) map[string]any
- type LocaleDefinition
- type LocaleMetadata
- type LocaleResolution
- type LocaleScope
- type MatchOptions
- type MatchStrategy
- type MeasurementPreferenceSet
- type Message
- type MessageMetadata
- type MessageVariant
- type MissingTranslationHandler
- type Option
- func EnablePluralFallbackSeeding() Option
- func EnablePluralization(rulePaths ...string) Option
- func WithCultureData(path string) Option
- func WithCultureOverride(locale, path string) Option
- func WithDefaultLocale(locale string) Option
- func WithFallback(locale string, fallbacks ...string) Option
- func WithFallbackResolver(resolver FallbackResolver) Option
- func WithFormatter(formatter Formatter) Option
- func WithFormatterLocales(locales ...string) Option
- func WithFormatterProvider(locale string, provider FormatterProvider) Option
- func WithLoader(loader Loader) Option
- func WithLocales(locales ...string) Option
- func WithStore(store Store) Option
- func WithTranslatorHooks(hooks ...TranslationHook) Option
- type PhoneDialPlan
- type PhoneFormatterFunc
- type PluralCategory
- type PluralCondition
- type PluralConditionOperator
- type PluralHookMetadata
- type PluralMissingEvent
- type PluralRange
- type PluralRule
- type PluralRuleSet
- type ResolveLocaleOptions
- type SimpleTranslator
- type SimpleTranslatorOption
- type StaticFallbackResolver
- type StaticStore
- type Store
- type TimeFormatRules
- type TranslateOption
- type TranslationCatalog
- type TranslationHook
- type TranslationHookFuncs
- type TranslationKey
- type Translations
- type Translator
- type TranslatorHookContext
- type TypedFormatterProvider
- type UnitPreference
Constants ¶
This section is empty.
Variables ¶
var ErrMissingTranslation = errors.New("i18n: missing translation")
ErrMissingTranslation indicates that no translation was found for locale/key.
var ErrNotImplemented = errors.New("i18n: not implemented")
ErrNotImplemented marks APIs that are intentionally stubbed during bootstrapping.
Functions ¶
func CultureHelpers ¶ added in v0.2.0
func CultureHelpers(service CultureService, localeKey string) map[string]any
CultureHelpers returns template helper functions for culture data
func FormatList ¶
func FormatOrdinal ¶
func FormatPhone ¶
func GeneratedCLDRLocales ¶ added in v0.2.0
func GeneratedCLDRLocales() []string
func LocaleParent ¶ added in v0.3.0
LocaleParent returns the closest parent locale, if any.
func LocaleParentChain ¶ added in v0.3.0
LocaleParentChain returns the parent locale chain from nearest parent to root.
func NormalizeAndSortLocales ¶ added in v0.3.0
NormalizeAndSortLocales canonicalizes, deduplicates, and sorts deterministically.
func NormalizeLocale ¶ added in v0.3.0
NormalizeLocale canonicalizes a locale identifier for shared use across the package.
func NormalizeLocales ¶ added in v0.3.0
NormalizeLocales canonicalizes, deduplicates, and preserves first-seen order.
func RegisterCLDRFormatters ¶ added in v0.2.0
func RegisterCLDRFormatters(registry *FormatterRegistry, locales ...string)
RegisterCLDRFormatters wires locale-specific helpers sourced from CLDR bundles.
func RegisterGeneratedCLDRFormatters ¶ added in v0.2.0
func RegisterGeneratedCLDRFormatters(registry *FormatterRegistry)
func RegisterPhoneDialPlan ¶ added in v0.2.0
func RegisterPhoneDialPlan(locale string, plan PhoneDialPlan)
RegisterPhoneDialPlan registers a dial plan for a locale using the shared formatter pipeline. The plan is converted into a formatter that formats numbers in the +<country> groups... pattern.
func RegisterPhoneFormatter ¶ added in v0.2.0
func RegisterPhoneFormatter(locale string, formatter PhoneFormatterFunc)
RegisterPhoneFormatter registers a custom phone formatter for the given locale. The formatter receives the resolved locale and raw input string.
func RegisterXTextFormatters ¶
func RegisterXTextFormatters(registry *FormatterRegistry, rulesProvider *FormattingRulesProvider, locales ...string)
RegisterXTextFormatters registers locale aware formatters backed by golang.org/x/text
func TemplateHelpers ¶
func TemplateHelpers(t Translator, cfg HelperConfig) map[string]any
TemplateHelpers exposes translator + formatter helpers for go-template.
For production use, supply a properly configured Registry via HelperConfig.Registry or use Config.TemplateHelpers() which automatically configures fallback resolution for regional locale variants (e.g., es-MX → es → en).
When cfg.Registry is nil, this function creates a minimal registry with automatic parent-chain fallback resolution (e.g., zh-Hant-HK → zh-Hant → zh).
Types ¶
type Config ¶
type Config struct {
DefaultLocale string
Locales []string
Loader Loader
Store Store
Resolver FallbackResolver
Formatter Formatter
Hooks []TranslationHook
// contains filtered or unexported fields
}
Config captures translator and formatter setup
func (*Config) BuildTranslator ¶
func (cfg *Config) BuildTranslator() (Translator, error)
func (*Config) CultureService ¶ added in v0.2.0
func (cfg *Config) CultureService() CultureService
CultureService returns the culture service
func (*Config) FormatterRegistry ¶ added in v0.2.0
func (cfg *Config) FormatterRegistry() *FormatterRegistry
func (*Config) LocaleCatalog ¶ added in v0.2.0
func (cfg *Config) LocaleCatalog() *LocaleCatalog
LocaleCatalog exposes the immutable locale metadata snapshot loaded from culture data.
func (*Config) TemplateHelpers ¶ added in v0.2.0
func (cfg *Config) TemplateHelpers(t Translator, helperCfg HelperConfig) map[string]any
type CultureData ¶ added in v0.2.0
type CultureData struct {
SchemaVersion string `json:"schema_version"`
DefaultLocale string `json:"default_locale"`
Locales map[string]LocaleDefinition `json:"locales"`
Currencies map[string]CurrencyInfo `json:"currencies"`
SupportNumbers map[string]string `json:"support_numbers"`
Lists map[string]map[string][]string `json:"lists"`
MeasurementPreferences map[string]MeasurementPreferenceSet `json:"measurement_preferences"`
FormattingRules map[string]FormattingRules `json:"formatting_rules"`
}
CultureData contains locale-specific business/cultural information
type CultureDataLoader ¶ added in v0.2.0
type CultureDataLoader struct {
// contains filtered or unexported fields
}
CultureDataLoader loads culture data from various sources
func NewCultureDataLoader ¶ added in v0.2.0
func NewCultureDataLoader(defaultPath string) *CultureDataLoader
NewCultureDataLoader creates a loader
func (*CultureDataLoader) AddOverride ¶ added in v0.2.0
func (l *CultureDataLoader) AddOverride(locale, path string)
AddOverride adds a locale-specific override file
func (*CultureDataLoader) Load ¶ added in v0.2.0
func (l *CultureDataLoader) Load() (*CultureData, error)
Load reads culture data from JSON files
type CultureService ¶ added in v0.2.0
type CultureService interface {
// GetCurrencyCode returns the currency code for a locale
GetCurrencyCode(locale string) (string, error)
// GetCurrency returns currency metadata for a locale
GetCurrency(locale string) (CurrencyInfo, error)
// GetSupportNumber returns the support contact for a locale
GetSupportNumber(locale string) (string, error)
// GetList returns a locale-specific list by name
GetList(locale, name string) ([]string, error)
// GetMeasurementPreference returns preferred units for a locale
GetMeasurementPreference(locale, measurementType string) (*UnitPreference, error)
// ConvertMeasurement converts a value to the preferred unit for a locale
ConvertMeasurement(locale string, value float64, fromUnit, measurementType string) (float64, string, string, error)
}
CultureService provides access to cultural/business data
func NewCultureService ¶ added in v0.2.0
func NewCultureService(data *CultureData, resolver FallbackResolver) CultureService
NewCultureService creates a culture service from data
type CurrencyFormatRules ¶ added in v0.2.0
type CurrencyFormatRules struct {
// Pattern: {symbol}, {amount}
Pattern string `json:"pattern"`
SymbolPosition string `json:"symbol_position"` // "before", "after"
DecimalSep string `json:"decimal_separator"`
ThousandSep string `json:"thousand_separator"`
Decimals int `json:"decimals"`
}
CurrencyFormatRules defines currency formatting
type CurrencyInfo ¶ added in v0.2.0
CurrencyInfo describes currency metadata for a locale.
type DatePatternRules ¶ added in v0.2.0
type DatePatternRules struct {
// Pattern uses placeholders: {day}, {month}, {year}
Pattern string `json:"pattern"`
DayFirst bool `json:"day_first"`
MonthStyle string `json:"month_style"` // "name", "number", "short"
}
DatePatternRules defines how dates are formatted
type FallbackResolver ¶
FallbackResolver resolves fallback locale chains
type FileLoader ¶
type FileLoader struct {
// contains filtered or unexported fields
}
func NewFileLoader ¶
func NewFileLoader(paths ...string) *FileLoader
func (*FileLoader) Load ¶
func (l *FileLoader) Load() (Translations, error)
func (*FileLoader) WithPluralRuleFiles ¶ added in v0.2.0
func (l *FileLoader) WithPluralRuleFiles(paths ...string) *FileLoader
func (*FileLoader) WithPluralRules ¶ added in v0.2.0
func (l *FileLoader) WithPluralRules(paths ...string) Loader
WithPluralRules satisfies the pluralRuleLoader contract used by config wiring.
type FormatterCapabilities ¶ added in v0.2.0
type FormatterFunc ¶
FormatterFunc adapts plain functions into Formatter
type FormatterProvider ¶
type FormatterRegistry ¶
type FormatterRegistry struct {
// contains filtered or unexported fields
}
FormatRegistry manages formatter functions and locale specific overrides
func NewFormatterRegistry ¶
func NewFormatterRegistry(opts ...FormatterRegistryOption) *FormatterRegistry
NewFormatterRegistry seeds a registry with default formatter implementations
func (*FormatterRegistry) Formatter ¶
func (r *FormatterRegistry) Formatter(name, locale string) (any, bool)
Formatter returns the helper implementation for the given name and locale
func (*FormatterRegistry) FuncMap ¶
func (r *FormatterRegistry) FuncMap(locale string) map[string]any
FUncMap returns all helper functions applicable to the locale
func (*FormatterRegistry) Register ¶
func (r *FormatterRegistry) Register(name string, fn any)
Register sets or replaces a default ipmlementtion for <name> helper
func (*FormatterRegistry) RegisterLocale ¶
func (r *FormatterRegistry) RegisterLocale(locale, name string, fn any)
RegisterLocale registers a locale specific ovveride for the <name> helper
func (*FormatterRegistry) RegisterProvider ¶
func (r *FormatterRegistry) RegisterProvider(locale string, provider FormatterProvider)
func (*FormatterRegistry) RegisterTypedProvider ¶ added in v0.2.0
func (r *FormatterRegistry) RegisterTypedProvider(locale string, provider TypedFormatterProvider)
type FormatterRegistryOption ¶ added in v0.2.0
type FormatterRegistryOption func(*formatterRegistryConfig)
func WithFormatterRegistryLocales ¶ added in v0.2.0
func WithFormatterRegistryLocales(locales ...string) FormatterRegistryOption
func WithFormatterRegistryProvider ¶ added in v0.2.0
func WithFormatterRegistryProvider(locale string, provider FormatterProvider) FormatterRegistryOption
func WithFormatterRegistryResolver ¶ added in v0.2.0
func WithFormatterRegistryResolver(resolver FallbackResolver) FormatterRegistryOption
func WithFormatterRegistryTypedProvider ¶ added in v0.2.0
func WithFormatterRegistryTypedProvider(locale string, provider TypedFormatterProvider) FormatterRegistryOption
func WithFormattingRulesProvider ¶ added in v0.2.0
func WithFormattingRulesProvider(provider *FormattingRulesProvider) FormatterRegistryOption
type FormattingDataLoader ¶ added in v0.2.0
type FormattingDataLoader interface {
Load(locale string) (*FormattingRules, error)
Available() []string
}
FormattingDataLoader loads formatting rules from embedded data
type FormattingRules ¶ added in v0.2.0
type FormattingRules struct {
Locale string `json:"locale"`
DatePatterns DatePatternRules `json:"date_patterns"`
CurrencyRules CurrencyFormatRules `json:"currency_rules"`
MonthNames []string `json:"month_names"`
TimeFormat TimeFormatRules `json:"time_format"`
}
FormattingRules contains all locale-specific formatting patterns
type FormattingRulesProvider ¶ added in v0.2.0
type FormattingRulesProvider struct {
// contains filtered or unexported fields
}
FormattingRulesProvider provides formatting rules for locales
func NewFormattingRulesProvider ¶ added in v0.2.0
func NewFormattingRulesProvider(cultureData *CultureData, resolver FallbackResolver) *FormattingRulesProvider
NewFormattingRulesProvider creates a provider from culture data
func (*FormattingRulesProvider) Get ¶ added in v0.2.0
func (p *FormattingRulesProvider) Get(locale string) *FormattingRules
Get loads formatting rules for a locale It tries exact match, then base language, then falls back to English
type HelperConfig ¶
type HelperConfig struct {
// LocaleKey selects the context key used to infer locale from template data.
LocaleKey string
// Registry allows callers to supply a custom formatter registry.
Registry *FormatterRegistry
// OnMissing controls the string returned when a translation is missing.
OnMissing MissingTranslationHandler
// TemplateHelperKey customizes the translator helper name (defaults to "translate").
TemplateHelperKey string
}
HelperConfig configures template helper exports
type HookedTranslator ¶
type HookedTranslator struct {
// contains filtered or unexported fields
}
func (*HookedTranslator) DefaultLocale ¶ added in v0.2.0
func (t *HookedTranslator) DefaultLocale() string
type Loader ¶
type Loader interface {
Load() (Translations, error)
}
Loader retrieves the translations used to seed a Store
type LoaderFunc ¶
type LoaderFunc func() (Translations, error)
LoaderFunc adapters allow bare functions to implement Loader interface
func (LoaderFunc) Load ¶
func (fn LoaderFunc) Load() (Translations, error)
Load implements Loader for LoaderFunc
type LocaleCatalog ¶ added in v0.2.0
type LocaleCatalog struct {
// contains filtered or unexported fields
}
LocaleCatalog is an immutable snapshot of locale metadata loaded from culture data.
func NewLocaleCatalogFromLocales ¶ added in v0.4.0
func NewLocaleCatalogFromLocales(defaultLocale string, locales []string) (*LocaleCatalog, error)
NewLocaleCatalogFromLocales builds a catalog from an explicit locale set and marks each supplied locale active. This is useful for request-bound matching against a caller-owned active locale list.
func (*LocaleCatalog) ActiveLocaleCodes ¶ added in v0.2.0
func (c *LocaleCatalog) ActiveLocaleCodes() []string
ActiveLocaleCodes returns all locales marked active, sorted alphabetically.
func (*LocaleCatalog) AllLocaleCodes ¶ added in v0.2.0
func (c *LocaleCatalog) AllLocaleCodes() []string
AllLocaleCodes returns every locale in the catalog, sorted alphabetically.
func (*LocaleCatalog) DecodeMetadata ¶ added in v0.3.0
func (c *LocaleCatalog) DecodeMetadata(locale string, out any) error
DecodeMetadata decodes locale metadata into a caller-owned output struct.
func (*LocaleCatalog) DefaultLocale ¶ added in v0.2.0
func (c *LocaleCatalog) DefaultLocale() string
DefaultLocale returns the configured default locale.
func (*LocaleCatalog) DisplayName ¶ added in v0.2.0
func (c *LocaleCatalog) DisplayName(locale string) string
DisplayName returns the human-friendly name for the requested locale.
func (*LocaleCatalog) Fallbacks ¶ added in v0.2.0
func (c *LocaleCatalog) Fallbacks(locale string) []string
Fallbacks returns the configured fallback chain for the locale.
func (*LocaleCatalog) Has ¶ added in v0.2.0
func (c *LocaleCatalog) Has(locale string) bool
Has reports whether the locale exists in the catalog.
func (*LocaleCatalog) IsActive ¶ added in v0.2.0
func (c *LocaleCatalog) IsActive(locale string) bool
IsActive reports whether the locale is marked active.
func (*LocaleCatalog) Locale ¶ added in v0.2.0
func (c *LocaleCatalog) Locale(locale string) (LocaleMetadata, bool)
Locale returns the full metadata payload for a locale.
func (*LocaleCatalog) Match ¶ added in v0.3.0
func (c *LocaleCatalog) Match(locale string) (LocaleMetadata, bool)
Match resolves a requested locale to a supported catalog locale. The default public behavior is exact-or-parent matching across all locales.
func (*LocaleCatalog) MatchAcceptLanguage ¶ added in v0.3.0
func (c *LocaleCatalog) MatchAcceptLanguage(header string) (LocaleMetadata, bool)
MatchAcceptLanguage resolves an Accept-Language header to the best supported locale across all configured locales.
func (*LocaleCatalog) MatchAcceptLanguageWithOptions ¶ added in v0.3.0
func (c *LocaleCatalog) MatchAcceptLanguageWithOptions(header string, opts MatchOptions) (LocaleMetadata, bool)
MatchAcceptLanguageWithOptions resolves an Accept-Language header to the best supported locale using explicit matching scope controls.
type LocaleDefinition ¶ added in v0.2.0
type LocaleDefinition struct {
DisplayName string `json:"display_name"`
Active *bool `json:"active,omitempty"`
Fallbacks []string `json:"fallbacks,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
LocaleDefinition represents the raw locale metadata as defined in culture data files.
type LocaleMetadata ¶ added in v0.2.0
type LocaleMetadata struct {
Code string
DisplayName string
Active bool
Fallbacks []string
Metadata map[string]any
}
LocaleMetadata exposes the immutable metadata for a single locale.
type LocaleResolution ¶ added in v0.3.0
type LocaleResolution struct {
Requested string
Canonical string
Matched string
Parents []string
Fallbacks []string
Default string
Chain []string
}
LocaleResolution describes the requested locale, any supported match, and the final ordered chain.
func ResolveLocale ¶ added in v0.3.0
func ResolveLocale(locale string, opts ResolveLocaleOptions) LocaleResolution
ResolveLocale builds an explicit, deterministic locale chain.
type LocaleScope ¶ added in v0.3.0
type LocaleScope int
LocaleScope controls whether matching considers all locales or only active locales.
const ( ScopeAll LocaleScope = iota ScopeActiveOnly )
type MatchOptions ¶ added in v0.3.0
type MatchOptions struct {
Scope LocaleScope
}
MatchOptions configures scoped supported-locale selection helpers.
type MatchStrategy ¶ added in v0.3.0
type MatchStrategy int
MatchStrategy controls how a requested locale is mapped to a supported locale.
const ( MatchExact MatchStrategy = iota MatchExactOrParent MatchBestFit )
type MeasurementPreferenceSet ¶ added in v0.2.0
type MeasurementPreferenceSet map[string]UnitPreference
MeasurementPreferenceSet groups unit preferences by measurement type.
type Message ¶ added in v0.2.0
type Message struct {
MessageMetadata
Variants map[PluralCategory]MessageVariant
}
func (*Message) SetContent ¶ added in v0.2.0
func (*Message) SetVariant ¶ added in v0.2.0
func (m *Message) SetVariant(category PluralCategory, vairant MessageVariant)
func (Message) Variant ¶ added in v0.2.0
func (m Message) Variant(category PluralCategory) (MessageVariant, bool)
type MessageMetadata ¶ added in v0.2.0
type MessageVariant ¶ added in v0.2.0
type MissingTranslationHandler ¶
MissingTranslationHandler decides what string should be emitted when Translator.Translate returns an error
type Option ¶
Option mutates Config during construction
func EnablePluralFallbackSeeding ¶ added in v0.2.0
func EnablePluralFallbackSeeding() Option
EnablePluralFallbackSeeding opts into automatic fallback chain seeding when pluralization is enabled.
func EnablePluralization ¶ added in v0.2.0
EnablePluralization wires pluralization defaults, optionally registering CLDR rule fixtures via loader aware options.
func WithCultureData ¶ added in v0.2.0
WithCultureData configures culture data loading
func WithCultureOverride ¶ added in v0.2.0
WithCultureOverride adds locale-specific culture data override
func WithDefaultLocale ¶
WithDefaultLocale sets the default locale in Config
func WithFallback ¶
func WithFallbackResolver ¶
func WithFallbackResolver(resolver FallbackResolver) Option
func WithFormatter ¶
func WithFormatterLocales ¶ added in v0.2.0
func WithFormatterProvider ¶ added in v0.2.0
func WithFormatterProvider(locale string, provider FormatterProvider) Option
func WithLoader ¶
func WithLocales ¶
WithLocales registers supported locales
func WithTranslatorHooks ¶
func WithTranslatorHooks(hooks ...TranslationHook) Option
type PhoneDialPlan ¶ added in v0.2.0
PhoneDialPlan describes how to normalize and format phone numbers for a locale. CountryCode should be digits without the leading plus sign. NationalPrefix is optional and stripped when present. Groups defines the digit grouping for the national significant number.
func DefaultPhoneDialPlan ¶ added in v0.2.0
func DefaultPhoneDialPlan(locale string) (PhoneDialPlan, bool)
DefaultPhoneDialPlan exposes the built-in dial plan for a locale if available. It first checks the exact locale key, then falls back to the base language.
type PhoneFormatterFunc ¶ added in v0.2.0
PhoneFormatterFunc formats a raw phone number string for a locale.
type PluralCategory ¶ added in v0.2.0
type PluralCategory string
const ( PluralZero PluralCategory = "zero" PluralOne PluralCategory = "one" PluralTwo PluralCategory = "two" PluralFew PluralCategory = "few" PluralMany PluralCategory = "many" PluralOther PluralCategory = "other" )
type PluralCondition ¶ added in v0.2.0
type PluralCondition struct {
Operand string
Mod int
Operator PluralConditionOperator
Values []float64
Ranges []PluralRange
}
type PluralConditionOperator ¶ added in v0.2.0
type PluralConditionOperator string
const ( OperatorEquals PluralConditionOperator = "eq" OperatorNotEquals PluralConditionOperator = "neq" OperatorIn PluralConditionOperator = "in" OperatorNotIn PluralConditionOperator = "not_in" OperatorWithin PluralConditionOperator = "within" OperatorNotWithin PluralConditionOperator = "not_within" )
type PluralHookMetadata ¶ added in v0.2.0
type PluralHookMetadata struct {
Category PluralCategory
Count any
Message string
Missing *PluralMissingEvent
}
type PluralMissingEvent ¶ added in v0.2.0
type PluralMissingEvent struct {
Requested PluralCategory
Fallback PluralCategory
}
type PluralRange ¶ added in v0.2.0
type PluralRule ¶ added in v0.2.0
type PluralRule struct {
Category PluralCategory
Groups [][]PluralCondition
}
type PluralRuleSet ¶ added in v0.2.0
type PluralRuleSet struct {
Locale string
DisplayName string
Parent string
Rules []PluralRule
}
func (*PluralRuleSet) Categories ¶ added in v0.2.0
func (set *PluralRuleSet) Categories() []PluralCategory
func (*PluralRuleSet) Clone ¶ added in v0.2.0
func (set *PluralRuleSet) Clone() *PluralRuleSet
Clone returns a deep copy of the rule set
type ResolveLocaleOptions ¶ added in v0.3.0
type ResolveLocaleOptions struct {
Catalog *LocaleCatalog
Resolver FallbackResolver
DefaultLocale string
MatchStrategy MatchStrategy
Scope LocaleScope
ExpandParents bool
ExpandFallbacks bool
IncludeDefault bool
}
ResolveLocaleOptions configures deterministic locale resolution.
type SimpleTranslator ¶
type SimpleTranslator struct {
// contains filtered or unexported fields
}
SimpleTranslator performs in memory lookups backed by a Store
func NewSimpleTranslator ¶
func NewSimpleTranslator(store Store, opts ...SimpleTranslatorOption) (*SimpleTranslator, error)
func (*SimpleTranslator) DefaultLocale ¶ added in v0.2.0
func (t *SimpleTranslator) DefaultLocale() string
func (*SimpleTranslator) Translate ¶
func (t *SimpleTranslator) Translate(locale, key string, args ...any) (string, error)
func (*SimpleTranslator) TranslateWithMetadata ¶ added in v0.2.0
type SimpleTranslatorOption ¶
type SimpleTranslatorOption func(*SimpleTranslator)
SimpleTranslatorOption configures SimpleTranslator
func WithTranslatorDefaultLocale ¶
func WithTranslatorDefaultLocale(locale string) SimpleTranslatorOption
func WithTranslatorFallbackResolver ¶
func WithTranslatorFallbackResolver(resolver FallbackResolver) SimpleTranslatorOption
func WithTranslatorFormatter ¶
func WithTranslatorFormatter(formatter Formatter) SimpleTranslatorOption
type StaticFallbackResolver ¶
type StaticFallbackResolver struct {
// contains filtered or unexported fields
}
StaticFallbackResolver initial imp
func NewStaticFallbackResolver ¶
func NewStaticFallbackResolver() *StaticFallbackResolver
func (*StaticFallbackResolver) Has ¶ added in v0.3.0
func (r *StaticFallbackResolver) Has(locale string) bool
Has reports whether a locale has an explicitly configured fallback chain, including an intentionally empty chain.
func (*StaticFallbackResolver) Resolve ¶
func (r *StaticFallbackResolver) Resolve(locale string) []string
Resolve returns a copy of the fallback chain for a locale
func (*StaticFallbackResolver) Set ¶
func (r *StaticFallbackResolver) Set(locale string, fallbacks ...string)
Set registers the fallback chain for a locale
type StaticStore ¶
type StaticStore struct {
// contains filtered or unexported fields
}
StaticStore is an in memory store, read only after cosntruction
func NewStaticStore ¶
func NewStaticStore(data Translations) *StaticStore
NewStaticStore builds an immutable snapthot from the given translations
func NewStaticStoreFromLoader ¶
func NewStaticStoreFromLoader(loader Loader) (*StaticStore, error)
NewStaticStoreFromLoader hydrates a StaticStore using the provided loader
func (*StaticStore) Get ¶
func (s *StaticStore) Get(locale, key string) (string, bool)
Get returns the the message template for locale/key
func (*StaticStore) Locales ¶
func (s *StaticStore) Locales() []string
Locales returns a slice with all locale codes
func (*StaticStore) Message ¶ added in v0.2.0
func (s *StaticStore) Message(locale, key string) (Message, bool)
func (*StaticStore) Rules ¶ added in v0.2.0
func (s *StaticStore) Rules(locale string) (*PluralRuleSet, bool)
type Store ¶
type Store interface {
// Get returns the message template for locale/key and ok=false if missing
Get(locale, key string) (string, bool)
// Message returns the full message payload for locale/key
Message(locale, key string) (Message, bool)
// Rules returns the plural rule set for the requested locale
Rules(locale string) (*PluralRuleSet, bool)
// Locales returns the list of locales known to the store
Locales() []string
}
Store exposes a read only access to translated mesasge templates
type TimeFormatRules ¶ added in v0.2.0
TimeFormatRules defines time formatting
type TranslateOption ¶ added in v0.2.0
type TranslateOption interface {
// contains filtered or unexported methods
}
TranslateOption configures translation behaviour (e.g. counts for plurals).
func WithCount ¶ added in v0.2.0
func WithCount(value any) TranslateOption
WithCount annotates a translation call with a quantity used for plural selection.
type TranslationCatalog ¶ added in v0.2.0
type TranslationCatalog struct {
Locale Locale
Messages map[string]Message
CardinalRules *PluralRuleSet
}
type TranslationHook ¶
type TranslationHook interface {
BeforeTranslate(ctx *TranslatorHookContext)
AfterTranslate(ctx *TranslatorHookContext)
}
type TranslationHookFuncs ¶
type TranslationHookFuncs struct {
Before func(ctx *TranslatorHookContext)
After func(ctx *TranslatorHookContext)
}
func (TranslationHookFuncs) AfterTranslate ¶
func (h TranslationHookFuncs) AfterTranslate(ctx *TranslatorHookContext)
func (TranslationHookFuncs) BeforeTranslate ¶
func (h TranslationHookFuncs) BeforeTranslate(ctx *TranslatorHookContext)
type TranslationKey ¶
TranslationKey models identifier metadata
type Translations ¶
type Translations map[string]*TranslationCatalog
type Translator ¶
Translator resolves a string for a given locale and message key.
func WrapTranslatorWithHooks ¶
func WrapTranslatorWithHooks(next Translator, hooks ...TranslationHook) Translator
type TranslatorHookContext ¶
type TranslatorHookContext struct {
Locale string
Key string
Args []any
Result string
Error error
Metadata map[string]any
}
func (*TranslatorHookContext) MetadataValue ¶
func (ctx *TranslatorHookContext) MetadataValue(key string) (any, bool)
func (*TranslatorHookContext) PluralMetadata ¶ added in v0.2.0
func (ctx *TranslatorHookContext) PluralMetadata() (PluralHookMetadata, bool)
PluralMetadata returns plural-specific hook metadata if present.
func (*TranslatorHookContext) SetMetadata ¶
func (ctx *TranslatorHookContext) SetMetadata(key string, value any)
type TypedFormatterProvider ¶ added in v0.2.0
Source Files
¶
- config.go
- culture.go
- culture_helpers.go
- culture_loader.go
- decorators.go
- errors.go
- fallback.go
- formatters.go
- formatters_cldr.go
- formatters_cldr_data.go
- formatters_cldr_generate.go
- formatters_data.go
- formatters_data_types.go
- formatters_registry.go
- formatters_xtext.go
- loaders.go
- locale_catalog.go
- locale_policy.go
- locale_utils.go
- phone_registry.go
- store.go
- template.go
- translator.go
- types.go