locale

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 9 Imported by: 0

README

Locale

arkoren.dev/core/http/middleware/locale negotiates the request language and passes it, with a message catalog, to arkoren.dev/foundation/validate so validation errors render in the client's language.

Given your spanish and brazilian message sets (validate.Messages), add language negotiation to an existing r router:

catalog := validate.Catalog{
	Default: "en",
	Locales: map[string]validate.Messages{
		"en":    validate.English(),
		"es":    spanish,
		"pt-BR": brazilian,
	},
}

r.Use(locale.Middleware(func(language *locale.Builder) {
	language.Catalog(catalog)
	language.QueryParam("lang")
	language.Cookie("lang")
}))

The locale is the first match of the query parameter, the cookie, then the Accept-Language header ordered by q-value. A tag matches a catalog locale exactly (pt-BR), then by base language (es-MX matches es); matching ignores case. Otherwise the catalog default applies, or en when it names none. Supported locales are the keys of Catalog.Locales.

Catalog tags must have ASCII language-tag shape: one to eight letters followed by optional alphanumeric subtags of one to eight characters. Matching also trims whitespace and accepts underscores in place of hyphens. Duplicate normalized keys such as pt-BR and pt_BR, invalid tags, or an invalid nonempty cookie name panic after all callbacks. Later callbacks may replace intermediate invalid settings. An explicitly empty catalog remains valid and falls back to en.

The middleware sets Content-Language and adds Accept-Language to Vary (plus Cookie when a cookie is configured). The headers are also added to the problem response context, so error responses carry them. Read the result with locale.FromContext(ctx). The context keeps the catalog key used for translations; the header trims that key and replaces catalog-only underscores with HTTP language-tag hyphens.

HTTP q-values are in [0, 1] with no more than three decimal digits; digits after 1 must be zero. Zero preferences, nonfinite or malformed values, and duplicate q parameters are ignored. Tag checks cover the basic ASCII shape, not the full BCP 47 grammar or a language-registry lookup.

Without Builder.QueryParam and Builder.Cookie those sources are off. Middleware() starts with the built-in English catalog. The cookie setting only names a cookie to read. This middleware does not write cookies and has no cookie duration or lifetime setting.

The validation overview introduces the schemas that use these messages.

Documentation

Overview

Package locale provides middleware that picks the response language from the request and hands it to validate to translate validation messages.

The locale comes from, in order, an optional query parameter, an optional cookie, and the Accept-Language header with its q-values. Each candidate is matched against the locales of the catalog, first exactly and then by base language ("es" for "es-MX"). Without a match the catalog default is used.

Catalog tags have ASCII language-tag shape. Case, surrounding whitespace, and underscores are normalized for matching; context keeps the original catalog key, while Content-Language trims whitespace and replaces underscores with hyphens. Invalid tags, ambiguous normalized keys, or invalid nonempty cookie names panic after all callbacks. An empty catalog falls back to English, and empty query/cookie names disable those selectors. The middleware only reads cookies; it does not issue cookies or configure their lifetime.

HTTP quality values must be zero or one with at most three decimal digits; only zeros may follow one. Malformed, nonfinite, duplicate, or q=0 preferences are ignored. Tag checks cover the basic ASCII shape, not the full BCP 47 grammar or a registry lookup.

Example:

routes := router.New()
routes.Use(locale.Middleware(func(language *locale.Builder) {
	language.QueryParam("lang")
	language.Cookie("language")
}))

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FromContext

func FromContext(ctx context.Context) string

FromContext returns the locale stored by Middleware, or an empty string when the context has none. It preserves the catalog key for translation lookup; Content-Language instead trims whitespace and replaces underscores with "-".

Example:

tag := locale.FromContext(request.Context())
fmt.Println(tag)

func Middleware

func Middleware(configure ...BuilderFunc) router.Middleware

Middleware returns middleware that resolves the request locale and stores it, with the catalog, in the request context for validate.

It sets Content-Language to the resolved locale and adds Accept-Language (and Cookie, when a cookie is configured) to Vary. The headers are also attached to the problem response context, so error responses carry them.

Retrieve the locale downstream with FromContext. Invalid catalog tags, ambiguous normalized keys, and invalid nonempty cookie names panic after all callbacks. The empty catalog and empty selector names retain their fallback/disabled meanings. Malformed HTTP quality values, including nonfinite numbers or duplicate q parameters, are ignored.

Example:

routes.Use(locale.Middleware(func(language *locale.Builder) {
	language.QueryParam("lang")
	language.Cookie("language")
}))

Types

type Builder

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

Builder configures Middleware before publication. Callbacks run directly once, synchronously in order on one fresh draft; nil entries panic. Retaining the draft cannot change published settings. Methods return the same draft.

Example:

r := router.New()
r.Use(locale.Middleware(func(language *locale.Builder) {
	language.QueryParam("lang")
}))

func (*Builder) Catalog

func (language *Builder) Catalog(catalog validate.Catalog) *Builder

Catalog holds the supported locales, which are its Locales keys, and the default locale. Middleware uses the built-in English messages. An empty Default falls back to "en"; an empty catalog remains valid. Keys and a nonempty Default must have language-tag shape: one to eight ASCII letters, followed by optional one-to-eight-character alphanumeric subtags. Matching ignores case, surrounding whitespace, and the distinction between "_" and "-". Two keys with the same normalized spelling are ambiguous and panic at publication, as do invalid tags. Message maps remain detached from the caller.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
catalog := validate.Catalog{
	Default: "en",
	Locales: map[string]validate.Messages{"en": validate.English()},
}
r.Use(locale.Middleware(func(language *locale.Builder) {
	language.Catalog(catalog)
}))

func (*Builder) Cookie

func (language *Builder) Cookie(name string) *Builder

Cookie names a cookie that selects the locale when the query parameter is absent or unsupported. Empty disables it. A nonempty name must pass net/http.Cookie.Valid; Middleware panics for an invalid final name after running every construction callback. This middleware never writes cookies and has no cookie lifetime or duration setting.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(locale.Middleware(func(language *locale.Builder) {
	language.Cookie("language")
}))

func (*Builder) QueryParam

func (language *Builder) QueryParam(name string) *Builder

QueryParam names a query parameter that selects the locale and wins over every other source. Empty disables it.

The setting replaces the previous value on this construction draft. Publication keeps independent settings; functions and services stay shared.

Example:

r := router.New()
r.Use(locale.Middleware(func(language *locale.Builder) {
	language.QueryParam("lang")
}))

type BuilderFunc

type BuilderFunc = func(*Builder)

BuilderFunc edits one locale construction draft. Policies run once, synchronously in order, before final tag and cookie-name validation. A supplied nil policy panics; an expanded nil slice supplies no policies. Catalog maps are detached at publication, including maps kept through a retained draft.

Example:

var selectLanguage locale.BuilderFunc = func(language *locale.Builder) {
	language.QueryParam("lang")
}
routes.Use(locale.Middleware(selectLanguage))

Directories

Path Synopsis
internal
negotiation
Package negotiation resolves original catalog keys from HTTP preferences.
Package negotiation resolves original catalog keys from HTTP preferences.

Jump to

Keyboard shortcuts

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