Documentation
¶
Index ¶
- Variables
- func DetectLanguage(cfg *config.Config) string
- func HasLanguage(code string) bool
- func Init(defaultLang string) error
- func Interpolate(template string, data map[string]interface{}) string
- func LanguageCodes() []string
- func LoadFromDirectory(bundle *Bundle, dir string) error
- func LoadTranslations(bundle *Bundle) error
- func LocaleFromContext(ctx context.Context) string
- func RegisterLanguage(locale *Locale)
- func WithLocale(ctx context.Context, locale string) context.Context
- type Bundle
- func (b *Bundle) AddMessages(lang string, messages MessageMap) error
- func (b *Bundle) AvailableLanguages() []string
- func (b *Bundle) DefaultLanguage() string
- func (b *Bundle) GetLocale(lang string) (*Locale, bool)
- func (b *Bundle) GetMessage(lang, id string) (*Message, error)
- func (b *Bundle) HasLanguage(lang string) bool
- func (b *Bundle) MessageCount(lang string) int
- func (b *Bundle) RegisterLocale(locale *Locale)
- type Cache
- type DateFormatter
- type FallbackChain
- type Locale
- type Localizer
- func (l *Localizer) ClearCache()
- func (l *Localizer) Language() string
- func (l *Localizer) Locale() *Locale
- func (l *Localizer) Localize(messageID string) string
- func (l *Localizer) LocalizePlural(messageID string, count int, data map[string]interface{}) string
- func (l *Localizer) LocalizeTemplate(messageID string, data map[string]interface{}) string
- type Manager
- func (m *Manager) AvailableLanguages() []string
- func (m *Manager) ClearCache()
- func (m *Manager) GetLanguage() string
- func (m *Manager) GetLocale() *Locale
- func (m *Manager) SetLanguage(lang string) error
- func (m *Manager) T(key string) string
- func (m *Manager) Tn(key string, count int, data map[string]interface{}) string
- func (m *Manager) Tpl(key string, data map[string]interface{}) string
- type Message
- type MessageMap
- type NumberFormatter
- type PluralForm
- func ArabicPlural(n int) PluralForm
- func ChinesePlural(n int) PluralForm
- func CzechPlural(n int) PluralForm
- func DefaultPlural(n int) PluralForm
- func EnglishPlural(n int) PluralForm
- func FrenchPlural(n int) PluralForm
- func GermanPlural(n int) PluralForm
- func ItalianPlural(n int) PluralForm
- func JapanesePlural(n int) PluralForm
- func PolishPlural(n int) PluralForm
- func PortuguesePlural(n int) PluralForm
- func RussianPlural(n int) PluralForm
- func SpanishPlural(n int) PluralForm
- func UkrainianPlural(n int) PluralForm
- type PluralFunc
- type Registry
- type Template
- type TranslationFile
- type ValidationError
- type ValidationResult
Constants ¶
This section is empty.
Variables ¶
var ( // ErrLanguageNotFound is returned when a requested language is not available. ErrLanguageNotFound = errors.New("language not found") // ErrMessageNotFound is returned when a translation key does not exist. ErrMessageNotFound = errors.New("message not found") // ErrInvalidLocale is returned when a locale code is malformed. ErrInvalidLocale = errors.New("invalid locale code") // ErrLoadFailed is returned when translation files fail to load. ErrLoadFailed = errors.New("failed to load translations") // ErrParseFailed is returned when a translation file cannot be parsed. ErrParseFailed = errors.New("failed to parse translation file") // ErrNoDefaultLanguage is returned when no default language is set. ErrNoDefaultLanguage = errors.New("no default language set") )
Functions ¶
func DetectLanguage ¶
DetectLanguage determines the language to use based on config and environment.
func HasLanguage ¶
HasLanguage checks if a language code is registered.
func Interpolate ¶
Interpolate replaces placeholders in a template string with values from data. Supports {key} syntax for variable interpolation.
func LanguageCodes ¶
func LanguageCodes() []string
LanguageCodes returns all registered language codes.
func LoadFromDirectory ¶
LoadFromDirectory loads translation files from a directory on disk. This allows overriding embedded translations with external files.
func LoadTranslations ¶
LoadTranslations loads all translation files into a bundle. First attempts to load from embedded files, then checks for external files.
func LocaleFromContext ¶
LocaleFromContext extracts the locale from context. Returns empty string if no locale is set.
func RegisterLanguage ¶
func RegisterLanguage(locale *Locale)
RegisterLanguage registers a locale in the global registry. This is typically called from init() functions in language files.
Types ¶
type Bundle ¶
type Bundle struct {
// contains filtered or unexported fields
}
Bundle holds all translation messages for all languages.
func (*Bundle) AddMessages ¶
func (b *Bundle) AddMessages(lang string, messages MessageMap) error
AddMessages adds translation messages for a language.
func (*Bundle) AvailableLanguages ¶
AvailableLanguages returns a list of all languages with loaded messages.
func (*Bundle) DefaultLanguage ¶
DefaultLanguage returns the default language code.
func (*Bundle) GetMessage ¶
GetMessage retrieves a message for a specific language and ID.
func (*Bundle) HasLanguage ¶
HasLanguage checks if a language has been loaded.
func (*Bundle) MessageCount ¶
MessageCount returns the number of messages for a language.
func (*Bundle) RegisterLocale ¶
RegisterLocale registers a locale configuration.
type Cache ¶
type Cache struct {
// contains filtered or unexported fields
}
Cache provides thread-safe caching for translated strings.
type DateFormatter ¶
type DateFormatter struct {
// contains filtered or unexported fields
}
DateFormatter formats dates and times according to locale rules.
func NewDateFormatter ¶
func NewDateFormatter(locale *Locale) *DateFormatter
NewDateFormatter creates a date formatter for a locale.
func (*DateFormatter) FormatDate ¶
func (f *DateFormatter) FormatDate(t time.Time, layout string) string
FormatDate formats a time according to the given layout.
func (*DateFormatter) FormatDateTime ¶
func (f *DateFormatter) FormatDateTime(t time.Time) string
FormatDateTime formats both date and time.
func (*DateFormatter) FormatRelative ¶
func (f *DateFormatter) FormatRelative(t time.Time) string
FormatRelative formats a time relative to now (e.g., "5 minutes ago"). This should use translated strings from the message catalog.
func (*DateFormatter) FormatTime ¶
func (f *DateFormatter) FormatTime(t time.Time) string
FormatTime formats just the time portion.
type FallbackChain ¶
type FallbackChain struct {
// contains filtered or unexported fields
}
FallbackChain defines a sequence of languages to try when looking up translations.
func NewFallbackChain ¶
func NewFallbackChain(preferred string, defaults ...string) *FallbackChain
NewFallbackChain creates a new fallback chain with a preferred language and defaults. Example: NewFallbackChain("pt-BR", "pt", "en") creates chain: pt-BR → pt → en
func (*FallbackChain) Languages ¶
func (f *FallbackChain) Languages() []string
Languages returns the ordered list of languages in the fallback chain.
type Locale ¶
type Locale struct {
// Tag is the BCP 47 language tag
Tag language.Tag
// Code is the short language code (e.g., "en", "es", "de")
Code string
// Name is the English name of the language
Name string
// NativeName is the language's name in its own language
NativeName string
// Direction is the text direction ("ltr" or "rtl")
Direction string
// PluralFunc is the plural rule function for this language
PluralFunc PluralFunc
}
Locale represents a language/region configuration.
func AvailableLanguages ¶
func AvailableLanguages() []*Locale
AvailableLanguages returns all registered locales.
func GetLanguage ¶
GetLanguage retrieves a registered locale by code.
func ParseLocale ¶
ParseLocale parses a language code and returns a Locale. Supports formats like "en", "en-US", "en_US".
type Localizer ¶
type Localizer struct {
// contains filtered or unexported fields
}
Localizer handles translation lookups for a specific language.
func NewLocalizer ¶
NewLocalizer creates a new Localizer for a language.
func (*Localizer) ClearCache ¶
func (l *Localizer) ClearCache()
ClearCache clears the localizer's cache.
func (*Localizer) LocalizePlural ¶
LocalizePlural translates a message with plural support.
type Manager ¶
type Manager struct {
// contains filtered or unexported fields
}
Manager is the global translation manager.
func (*Manager) AvailableLanguages ¶
AvailableLanguages returns all loaded languages.
func (*Manager) ClearCache ¶
func (m *Manager) ClearCache()
ClearCache clears all translation caches.
func (*Manager) GetLanguage ¶
GetLanguage returns the current language code.
func (*Manager) SetLanguage ¶
SetLanguage changes the current language.
type Message ¶
type Message struct {
// ID is the unique identifier for this message (e.g., "composer.title")
ID string `json:"id"`
// Description provides context for translators
Description string `json:"description,omitempty"`
// Hash is an optional content hash for tracking changes
Hash string `json:"hash,omitempty"`
// Zero form is used when count is exactly 0 (optional)
Zero string `json:"zero,omitempty"`
// One form is used for singular (count == 1)
One string `json:"one,omitempty"`
// Two form is used for dual (count == 2) in some languages
Two string `json:"two,omitempty"`
// Few form is used for small counts in some languages (e.g., Polish)
Few string `json:"few,omitempty"`
// Many form is used for larger counts in some languages (e.g., Russian)
Many string `json:"many,omitempty"`
// Other is the default form used when no specific plural form matches
Other string `json:"other,omitempty"`
}
Message represents a translatable message with support for plural forms.
func (*Message) GetDefault ¶
GetDefault returns the most appropriate default text (tries Other, then One).
func (*Message) GetText ¶
func (m *Message) GetText(form PluralForm) string
GetText returns the appropriate text for the given plural form.
type MessageMap ¶
MessageMap maps message IDs to Message structs.
func ParseJSON ¶
func ParseJSON(data []byte) (MessageMap, error)
ParseJSON parses a JSON translation file and returns a MessageMap.
type NumberFormatter ¶
type NumberFormatter struct {
// contains filtered or unexported fields
}
NumberFormatter formats numbers according to locale rules.
func NewNumberFormatter ¶
func NewNumberFormatter(locale *Locale) *NumberFormatter
NewNumberFormatter creates a formatter for a locale.
func (*NumberFormatter) FormatFileSize ¶
func (f *NumberFormatter) FormatFileSize(bytes int64) string
FormatFileSize formats a byte count as a human-readable size.
func (*NumberFormatter) FormatFloat ¶
func (f *NumberFormatter) FormatFloat(n float64, precision int) string
FormatFloat formats a float64 with the specified precision.
func (*NumberFormatter) FormatInt ¶
func (f *NumberFormatter) FormatInt(n int) string
FormatInt formats an integer according to locale rules.
func (*NumberFormatter) FormatInt64 ¶
func (f *NumberFormatter) FormatInt64(n int64) string
FormatInt64 formats an int64 according to locale rules.
func (*NumberFormatter) FormatPercent ¶
func (f *NumberFormatter) FormatPercent(n float64) string
FormatPercent formats a number as a percentage (0.5 -> "50%").
type PluralForm ¶
type PluralForm int
PluralForm represents the different plural categories.
const ( // Zero is used when count is exactly 0 Zero PluralForm = iota // One is used for singular (typically count == 1) One // Two is used for dual (count == 2) in some languages Two // Few is used for small counts in some languages Few // Many is used for larger counts in some languages Many // Other is the default/fallback form Other )
func ArabicPlural ¶
func ArabicPlural(n int) PluralForm
ArabicPlural implements plural rules for Arabic. Rule: zero (n == 0)
one (n == 1) two (n == 2) few (n mod 100 in 3..10) many (n mod 100 in 11..99) other (everything else)
func ChinesePlural ¶
func ChinesePlural(n int) PluralForm
ChinesePlural implements plural rules for Chinese. Rule: other (always - no plural distinction)
func CzechPlural ¶
func CzechPlural(n int) PluralForm
CzechPlural implements plural rules for Czech. Rule: one (n == 1)
few (n in 2..4) many (everything else)
func DefaultPlural ¶
func DefaultPlural(n int) PluralForm
DefaultPlural is a simple plural function (English-like: 1 = one, else = other).
func EnglishPlural ¶
func EnglishPlural(n int) PluralForm
EnglishPlural implements plural rules for English. Rule: one (n == 1), other (everything else)
func FrenchPlural ¶
func FrenchPlural(n int) PluralForm
FrenchPlural implements plural rules for French. Rule: one (n == 0 or n == 1), other (everything else)
func GermanPlural ¶
func GermanPlural(n int) PluralForm
GermanPlural implements plural rules for German. Rule: one (n == 1), other (everything else)
func ItalianPlural ¶
func ItalianPlural(n int) PluralForm
ItalianPlural implements plural rules for Italian. Rule: one (n == 1), other (everything else)
func JapanesePlural ¶
func JapanesePlural(n int) PluralForm
JapanesePlural implements plural rules for Japanese. Rule: other (always - no plural distinction)
func PolishPlural ¶
func PolishPlural(n int) PluralForm
PolishPlural implements plural rules for Polish. Rule: one (n == 1)
few (n mod 10 in 2..4 and n mod 100 not in 12..14) many (everything else)
func PortuguesePlural ¶
func PortuguesePlural(n int) PluralForm
PortuguesePlural implements plural rules for Portuguese. Rule: one (n == 0 or n == 1), other (everything else)
func RussianPlural ¶
func RussianPlural(n int) PluralForm
RussianPlural implements plural rules for Russian. Rule: one (n mod 10 == 1 and n mod 100 != 11)
few (n mod 10 in 2..4 and n mod 100 not in 12..14) many (everything else)
func SpanishPlural ¶
func SpanishPlural(n int) PluralForm
SpanishPlural implements plural rules for Spanish. Rule: one (n == 1), other (everything else)
func UkrainianPlural ¶
func UkrainianPlural(n int) PluralForm
UkrainianPlural implements plural rules for Ukrainian. Rule: one (n mod 10 == 1 and n mod 100 != 11)
few (n mod 10 in 2..4 and n mod 100 not in 12..14) many (everything else)
Same as Russian
func (PluralForm) String ¶
func (p PluralForm) String() string
String returns the string representation of the plural form.
type PluralFunc ¶
type PluralFunc func(n int) PluralForm
PluralFunc is a function that returns the appropriate plural form for a count.
type Registry ¶
type Registry struct {
// contains filtered or unexported fields
}
Registry holds all registered language locales.
type Template ¶
type Template struct {
// contains filtered or unexported fields
}
Template represents a parsed template string with placeholders.
func NewTemplate ¶
NewTemplate parses a template string and returns a Template.
type TranslationFile ¶
type TranslationFile struct {
Language string `json:"language"`
Messages map[string]interface{} `json:"messages"`
}
TranslationFile represents the structure of a JSON translation file.
type ValidationError ¶
ValidationError represents a validation issue.
type ValidationResult ¶
type ValidationResult struct {
Valid bool
Errors []ValidationError
Missing map[string][]string // lang -> missing keys
Extra map[string][]string // lang -> extra keys
}
ValidationResult contains the results of validating translation files.
func ValidateTranslations ¶
func ValidateTranslations(bundle *Bundle, baseLang string) *ValidationResult
ValidateTranslations validates all translations against a base language. Checks for missing keys, extra keys, and consistency.
func (*ValidationResult) String ¶
func (v *ValidationResult) String() string
String returns a human-readable validation report.