Documentation
¶
Overview ¶
Package i18n owns shared locale identities, immutable UI catalogs, request locale resolution and bounded plain-text formatting. Model content uses the same locale snapshots with its own separate fallback policy.
Index ¶
- Constants
- func ParameterName(name string) bool
- func ReadTemplates(ctx context.Context, source fs.FS, locales LocaleCatalog) (map[LocaleID]map[MessageKey]Template, error)
- func ValidateLocaleCatalog(c LocaleCatalog) error
- func WithLocale(ctx context.Context, catalog LocaleCatalog, locale LocaleID) (context.Context, error)
- type Argument
- type Catalog
- func (c *Catalog) Accepts(d MessageDefinition) error
- func (c *Catalog) Definition(key MessageKey) (MessageDefinition, bool)
- func (c *Catalog) Definitions() []MessageDefinition
- func (c *Catalog) FormatDynamic(ctx context.Context, locale LocaleID, key MessageKey, args map[string]Argument) (Result, error)
- func (c *Catalog) Label(ctx context.Context, locale LocaleID, key MessageKey) (string, error)
- func (c *Catalog) Resolve(preferred string, acceptLanguage string) (LocaleID, error)
- func (c *Catalog) Snapshot(ctx context.Context) (LocaleSet, error)
- func (c *Catalog) Validate() error
- type CatalogOptions
- type LocaleCatalog
- type LocaleID
- type LocaleRequirement
- type LocaleResolver
- type LocaleSet
- func (s LocaleSet) Contains(id LocaleID) bool
- func (s LocaleSet) Default() LocaleID
- func (s LocaleSet) Fallbacks(requested LocaleID) ([]LocaleID, error)
- func (s LocaleSet) Locales() []LocaleID
- func (s LocaleSet) Match(id LocaleID) (LocaleID, bool)
- func (s LocaleSet) MatchAcceptLanguage(header string) (LocaleID, bool)
- func (s LocaleSet) MatchTag(text string) (LocaleID, bool)
- func (s LocaleSet) Snapshot(ctx context.Context) (LocaleSet, error)
- func (s LocaleSet) Validate() error
- type MessageArgument
- type MessageDefinition
- type MessageKey
- type MessageRecipe
- type Parameter
- type ParameterKind
- type PluralForm
- type PluralKind
- type Preference
- type PreferenceSource
- type PreparedMessage
- type Resolution
- type Result
- type Template
Constants ¶
const ( MaxMessages = 10000 MaxParameters = 64 MaxTextBytes = 64 << 10 MaxCatalogBytes = 16 << 20 )
const ( MaxAcceptLanguageBytes = 8192 MaxAcceptLanguageCandidates = 64 )
MaxAcceptLanguageBytes and MaxAcceptLanguageCandidates bound header parsing.
const (
MaxCatalogFiles = 1024
)
Catalog directory bounds. Raw directory listings are bounded separately from catalog files so ignored entries cannot force unbounded materialization.
const MaxLocales = 64
Variables ¶
This section is empty.
Functions ¶
func ParameterName ¶
ParameterName is shared by generated declarations and catalog placeholders.
func ReadTemplates ¶
func ReadTemplates(ctx context.Context, source fs.FS, locales LocaleCatalog) (map[LocaleID]map[MessageKey]Template, error)
ReadTemplates reads a catalog tree with Load's layout, limits and rules but without message definitions, so an application can declare its own keys before NewCatalog compiles the templates against them. Locale directories must belong to locales; duplicate JSON names, flattened keys and keys repeated across files fail with fault.Invalid naming the locale, file and key. Plural leaves become Template.Forms; their forms are checked when NewCatalog compiles them against a declaration. The result is owned by the caller.
func ValidateLocaleCatalog ¶
func ValidateLocaleCatalog(c LocaleCatalog) error
ValidateLocaleCatalog rejects nil locale catalogs, including typed nil values.
func WithLocale ¶
func WithLocale(ctx context.Context, catalog LocaleCatalog, locale LocaleID) (context.Context, error)
WithLocale records an explicitly supported locale on this context only.
Types ¶
type Argument ¶
type Argument struct {
// contains filtered or unexported fields
}
Argument is an explicit dynamic formatting value. Its zero value is invalid. Text is plain text; applications must escape the completed message for its output context. Values are substituted once and never interpreted as templates.
type Catalog ¶
type Catalog struct {
// contains filtered or unexported fields
}
Catalog is an immutable UI-message catalog and the same LocaleCatalog used by model content. It creates no goroutines and owns no open resources.
func Load ¶
func Load(ctx context.Context, source fs.FS, locales LocaleCatalog, options CatalogOptions, definitions ...MessageDefinition) (*Catalog, error)
Load reads locale/*.json from an explicit FS root (including embed.FS). Nested objects flatten with dots; plural leaves are {"$plural":{"one":..., "other":...}}. Dot entries (.DS_Store, .git, .gitkeep) at any level and non-.json regular files are ignored; root .json files, nested directories, symlinks, duplicate keys/files, unknown messages/locales, malformed leaves and excess resources fail construction atomically. Every failure names its locale, file and key where known. Filesystem callbacks are isolated and awaited through actual return.
func NewCatalog ¶
func NewCatalog(ctx context.Context, locales LocaleCatalog, options CatalogOptions, definitions []MessageDefinition, messages map[LocaleID]map[MessageKey]Template) (*Catalog, error)
NewCatalog creates a message catalog from locale configuration, definitions, and templates.
func (*Catalog) Accepts ¶
func (c *Catalog) Accepts(d MessageDefinition) error
Accepts checks the complete parameter/plural signature, not just key identity. Typed adapters use it before evaluating argument encoders. Declarations that are already name-sorted (all framework-built ones) are compared without copying; equality with a registered, validated declaration proves validity.
func (*Catalog) Definition ¶
func (c *Catalog) Definition(key MessageKey) (MessageDefinition, bool)
Definition returns an owned signature and whether it is registered.
func (*Catalog) Definitions ¶
func (c *Catalog) Definitions() []MessageDefinition
Definitions returns owned definition snapshots sorted by message key.
func (*Catalog) FormatDynamic ¶
func (c *Catalog) FormatDynamic(ctx context.Context, locale LocaleID, key MessageKey, args map[string]Argument) (Result, error)
FormatDynamic is the explicit runtime-key boundary. All arguments are required and must exactly match the registered signature, even for a missing message. Lookup tries the requested locale, its supported parents (en-GB → en), then the configured fallback; it never tries unrelated supported locales.
func (*Catalog) Resolve ¶
Resolve prefers an explicitly selected locale, then quality-sorted header candidates, then the configured default. Regional/extension tags may fall back to a supported parent; unrelated sibling locales are never selected. Malformed/zero-quality candidates are ignored. This is locale selection, not HTTP 406 negotiation; absence of an acceptable candidate uses the default. LocaleResolver composes the same steps with typed stored preferences.
type CatalogOptions ¶
type CatalogOptions struct{ Fallback LocaleID }
CatalogOptions selects the UI fallback, independently of model-content LocaleSet.Fallbacks. Empty Fallback selects the configured default locale.
type LocaleCatalog ¶
type LocaleCatalog interface {
// Snapshot returns the current locale set for the supplied context.
Snapshot(context.Context) (LocaleSet, error)
}
LocaleCatalog returns one consistent supported/default snapshot per operation. Implementations are borrowed, concurrent-safe and context-aware. Snapshot must not resolve a process-global or goroutine-global request locale.
type LocaleID ¶
type LocaleID string
LocaleID identifies a canonical locale.
func ParseLocale ¶
ParseLocale normalizes a BCP 47 tag. It does not grant membership in a supported-locale catalog. Operations require both validity and membership.
func RequestLocale ¶
RequestLocale returns the locale attached to a context and whether it is present; nil contexts return false.
type LocaleRequirement ¶
type LocaleRequirement uint8
LocaleRequirement selects which supported locales locale-keyed input, such as translated model text, must supply with nonempty text. The zero value requires none.
const ( OptionalLocales LocaleRequirement = iota DefaultLocale AllLocales )
func (LocaleRequirement) Required ¶
func (r LocaleRequirement) Required(locales LocaleSet) []LocaleID
Required returns the locales of one catalog snapshot that r requires, in the snapshot's order.
func (LocaleRequirement) Validate ¶
func (r LocaleRequirement) Validate() error
Validate checks that the locale requirement is supported.
type LocaleResolver ¶
type LocaleResolver[S any] struct { // contains filtered or unexported fields }
LocaleResolver applies ordered preferences, then the catalog default, against one supported-locale snapshot per call. It is immutable, creates no goroutines for framework catalogs and is safe to share across requests and workers. HTTP typically uses ContextLocale, a stored user preference and AcceptLanguage; mail and notifications use a recipient preference without a request header.
func NewLocaleResolver ¶
func NewLocaleResolver[S any](locales LocaleCatalog, steps ...Preference[S]) (*LocaleResolver[S], error)
NewLocaleResolver validates and copies a bounded preference sequence, rejecting duplicate sources.
func (*LocaleResolver[S]) Resolve ¶
func (r *LocaleResolver[S]) Resolve(ctx context.Context, subject S) (Resolution, error)
Resolve selects the first supported preference for subject, or the default. Unsupported preferences defer; preference failures and cancellation return an error instead of silently choosing the default.
func (*LocaleResolver[S]) WithResolvedLocale ¶
func (r *LocaleResolver[S]) WithResolvedLocale(ctx context.Context, subject S) (context.Context, Resolution, error)
WithResolvedLocale resolves subject and records the selection on ctx, so later formatting, validation and model-content reads use the same locale.
type LocaleSet ¶
type LocaleSet struct {
// contains filtered or unexported fields
}
LocaleSet is an immutable snapshot. Its zero value is invalid. It also implements LocaleCatalog for applications with a static configured set.
func NewLocaleSet ¶
NewLocaleSet copies, sorts, and validates a nonempty locale list containing the default, rejecting duplicates.
func SnapshotLocales ¶
func SnapshotLocales(ctx context.Context, c LocaleCatalog) (LocaleSet, error)
SnapshotLocales isolates extension panics/Goexit and waits for actual return. Managers call it inside their own bounded operation lifetime. The framework's immutable LocaleSet and *Catalog run no application code, so they are read directly without an isolation goroutine.
func (LocaleSet) Fallbacks ¶
Fallbacks returns requested, its supported regional parents (en-GB → en, never across a script subtag), the default, then remaining supported locales in lexical order, without duplicates. Unsupported requested IDs fail.
func (LocaleSet) Match ¶
Match returns id when it is supported, otherwise its nearest supported parent tag (en-GB → en, zh-Hant-TW → zh-Hant). A language-script tag such as zh-Hant or sr-Latn has no parent, so fallback never switches writing system. Unrelated siblings are never selected. This is the single parent-locale rule shared by request resolution, UI catalog lookup and model-content fallback.
func (LocaleSet) MatchAcceptLanguage ¶
MatchAcceptLanguage selects the first supported locale (or supported parent) from quality-sorted Accept-Language candidates. "*" selects the default. Oversized headers, malformed and zero-quality candidates are ignored; ties keep header order. It reports false when nothing matches.
func (LocaleSet) MatchTag ¶
MatchTag parses external BCP 47 text and applies Match. Malformed or unsupported text reports false rather than an error.
type MessageArgument ¶
type MessageArgument struct {
Name string `json:"name"`
Kind ParameterKind `json:"kind"`
Value string `json:"value"`
}
MessageArgument is a serialized declaration argument, never an input capture. Numbers retain decimal text instead of passing through float64.
type MessageDefinition ¶
type MessageDefinition struct {
Key MessageKey `json:"key"`
Parameters []Parameter `json:"parameters,omitempty"`
Plural string `json:"plural,omitempty"`
Kind PluralKind `json:"plural_kind,omitempty"`
}
MessageDefinition is the explicit dynamic declaration boundary. Generated typed messages derive it from their existing JSON contract. Plural names one numeric parameter; Kind is empty unless Plural is set.
func DiscoverDefinitions ¶ added in v0.3.0
func DiscoverDefinitions(ctx context.Context, source fs.FS, locales LocaleCatalog) ([]MessageDefinition, error)
DiscoverDefinitions reads a catalog tree with ReadTemplates and discovers dynamic message definitions from its template placeholders and plural forms. An explicit LocaleCatalog is required; all declared supported locales must be present. Plural forms across all locales must contain exactly one distinct placeholder, which becomes numeric. Messages needing additional plural-form arguments must use an explicit MessageDefinition.Plural in a shared catalog instead.
func (MessageDefinition) Validate ¶
func (d MessageDefinition) Validate() error
Validate checks the message definition and returns a keyed definition error on failure.
type MessageKey ¶
type MessageKey string
MessageKey identifies a UI message independently of its locale. Generated message declarations and feature labels share this identity; a cast is an explicit dynamic-key boundary and does not prove catalog membership.
func (MessageKey) Validate ¶
func (k MessageKey) Validate() error
Validate checks that the message key is a semantic identifier.
type MessageRecipe ¶
type MessageRecipe struct {
Definition MessageDefinition `json:"definition"`
Arguments []MessageArgument `json:"arguments,omitempty"`
Fallback map[PluralForm]string `json:"fallback"`
LiteralFallback bool `json:"literal_fallback,omitempty"`
}
MessageRecipe is the owned metadata for a prepared message. Fallback uses English plural forms, including Other; nonplural messages have only Other.
func (MessageRecipe) Prepare ¶
func (r MessageRecipe) Prepare() (PreparedMessage, error)
Prepare validates an exported recipe without retaining caller-owned data.
type Parameter ¶
type Parameter struct {
Name string `json:"name"`
Kind ParameterKind `json:"kind"`
}
Parameter describes a declared argument, never a received argument value.
type ParameterKind ¶
type ParameterKind string
ParameterKind identifies a message parameter's value kind.
const ( TextParameter ParameterKind = "text" NumberParameter ParameterKind = "number" BooleanParameter ParameterKind = "boolean" )
type PluralForm ¶
type PluralForm string
PluralForm identifies a plural form.
const ( Other PluralForm = "other" Zero PluralForm = "zero" One PluralForm = "one" Two PluralForm = "two" Few PluralForm = "few" Many PluralForm = "many" )
type PluralKind ¶
type PluralKind string
PluralKind selects a message's pluralization kind.
const ( Cardinal PluralKind = "cardinal" Ordinal PluralKind = "ordinal" )
type Preference ¶
type Preference[S any] struct { // contains filtered or unexported fields }
Preference is one ordered locale-selection step for a typed subject, such as an HTTP request, an authenticated user or a notification recipient. Its zero value is invalid. Construct steps with ContextLocale, Preferred or AcceptLanguage; each step either selects a supported locale or defers.
func AcceptLanguage ¶
func AcceptLanguage[S any](header func(S) string) Preference[S]
AcceptLanguage adapts a raw Accept-Language header value supplied by the transport, using the same quality ordering, bounds and parent matching as LocaleSet.MatchAcceptLanguage. An absent or unmatched header defers.
func ContextLocale ¶
func ContextLocale[S any]() Preference[S]
ContextLocale selects the locale already recorded by WithLocale on the operation context, for example by an earlier middleware or explicit caller.
func Preferred ¶
func Preferred[S any](source PreferenceSource, lookup func(context.Context, S) (LocaleID, bool, error)) Preference[S]
Preferred adapts an explicit or stored preference, such as a user's profile locale. The lookup returns false when the subject has no preference. A stored locale that is no longer supported falls back to its nearest supported parent or defers to the next step. A malformed stored value, such as en_US, is no preference: the step defers and Resolution.Ignored names it, so one bad profile value never breaks every request of that user. Lookup errors stop resolution and never select the default. The lookup is application code: panics are contained without a goroutine, it must honor ctx and be safe for concurrent use.
func (Preference[S]) Source ¶
func (p Preference[S]) Source() PreferenceSource
Source returns the preference source identifier.
func (Preference[S]) Validate ¶
func (p Preference[S]) Validate() error
Validate checks that the preference has a source and matching callback.
type PreferenceSource ¶
type PreferenceSource string
PreferenceSource names the step that selected a locale, for Vary/cache policy and diagnostics. ContextSource, AcceptLanguageSource and DefaultSource are reserved; Preferred steps use application names such as "user" or "tenant".
const ( ContextSource PreferenceSource = "context" AcceptLanguageSource PreferenceSource = "accept_language" DefaultSource PreferenceSource = "default" MaxPreferences = 16 )
type PreparedMessage ¶
type PreparedMessage struct {
// contains filtered or unexported fields
}
PreparedMessage owns validated arguments and an already compiled English fallback. It is immutable and safe to share across requests. Prefer the generated message.Message[A].Bind adapter when authoring application messages.
func PrepareLiteralMessage ¶
func PrepareLiteralMessage(definition MessageDefinition, args map[string]Argument, text string) (PreparedMessage, error)
PrepareLiteralMessage preserves text literally, including template delimiters.
func PrepareMessage ¶
func PrepareMessage(definition MessageDefinition, args map[string]Argument, fallback Template) (PreparedMessage, error)
PrepareMessage is the explicit dynamic construction boundary. It snapshots its inputs and rejects incomplete signatures and invalid fallback templates.
func (PreparedMessage) Description ¶
func (m PreparedMessage) Description() MessageRecipe
Description returns an owned snapshot of the message recipe.
func (PreparedMessage) Format ¶
func (m PreparedMessage) Format(ctx context.Context, catalog *Catalog, locale LocaleID) (Result, error)
Format tries the supplied catalog (requested locale, supported parents, then its configured fallback), then this message's English fallback. An unregistered key also uses the English fallback; a conflicting registered signature is an error. Nil catalog selects English. Arguments were validated at preparation, so formatting only checks the catalog signature once.
func (PreparedMessage) Validate ¶
func (m PreparedMessage) Validate() error
Validate checks that the prepared message has fallback data.
func (PreparedMessage) WithText ¶
func (m PreparedMessage) WithText(name, value string) (PreparedMessage, error)
WithText replaces an existing text argument in a new message. Missing names are ignored, letting a presenter supply optional standard label arguments. The immutable definition and fallback are shared; only arguments are copied.
type Resolution ¶
type Resolution struct {
Locale LocaleID
Source PreferenceSource
Ignored PreferenceSource
}
Resolution is the selected supported locale and the step that selected it. Ignored names the first Preferred step whose stored value was malformed and skipped; it is a diagnostic for repairing that value and grants nothing.
type Result ¶
Result makes missing/fallback diagnostics explicit without logging values or aborting unrelated requests. Locale is empty only when no translation exists.
type Template ¶
type Template struct {
Text string
Forms map[PluralForm]string
}
Template is either plain text or a plural form set. A plural template must include Other, and its registered message must declare the numeric parameter. Text and Forms cannot be combined. Catalog construction copies all data.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package message connects generated argument structs to i18n through the same typed JSON descriptor used by runtime codecs and client contract exporters.
|
Package message connects generated argument structs to i18n through the same typed JSON descriptor used by runtime codecs and client contract exporters. |
|
Package numberformat presents exact decimals, percentages and money for one locale.
|
Package numberformat presents exact decimals, percentages and money for one locale. |