Documentation
¶
Overview ¶
Package alx parses, sorts and matches HTTP Accept-Language headers (RFC 9110 / RFC 4647).
The core package depends only on the standard library. Framework adapters live in separate submodules (github.com/bakhod1r/alx/gin, /fiber, /echo, /iris, /beego, /fasthttp) so importing alx never pulls a web framework into your build.
Basic matching:
tag, ok := alx.Best(r.Header.Get("Accept-Language"), []string{"en", "uz", "ru"})
Multi-source resolution (URL segment, query, cookie, header, default):
res := alx.NewResolver(
alx.WithSupported("en", "uz", "ru"),
alx.WithURL(),
alx.WithQuery("lang"),
alx.WithCookie("lang"),
alx.WithHeader(),
alx.WithDefault("en"),
).ResolveRequest(r)
Index ¶
- func Best(header string, supported []string) (string, bool)
- func Canonical(tag string) string
- func Fallbacks(tag string) []string
- func Match(header string, supported []string) (string, bool)
- func MatchWith(header string, supported []string, strategy MatchStrategy) (string, bool)
- func Normalize(tag string) string
- func PrimaryLanguage(header string) string
- func SetContentLanguage(w http.ResponseWriter, lang string)
- func SetVary(w http.ResponseWriter)
- func Sort(langs []Language)
- func Validate(header string) error
- type Language
- type MatchStrategy
- type ParseError
- type Resolution
- type Resolver
- type ResolverOption
- func WithCookie(name string) ResolverOption
- func WithDefault(lang string) ResolverOption
- func WithFallback(tag, fallback string) ResolverOption
- func WithHeader(headers ...string) ResolverOption
- func WithQuery(param string) ResolverOption
- func WithSupported(langs ...string) ResolverOption
- func WithURL() ResolverOption
- type Source
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Best ¶
Best matches an Accept-Language header against a list of supported languages using the default Lookup strategy, returning the best match.
func Canonical ¶
Canonical transforms the input tag into a canonical format by replacing underscores with dashes and then applying Normalization.
func Fallbacks ¶
Fallbacks generates a slice of language tags representing the fallback chain for a given tag. For example, "zh-Hant-TW" results in ["zh-Hant-TW", "zh-Hant", "zh"].
func MatchWith ¶
func MatchWith(header string, supported []string, strategy MatchStrategy) (string, bool)
MatchWith matches an Accept-Language header against a list of supported languages using the specified matching strategy.
func Normalize ¶
Normalize normalizes a language tag to its canonical casing. It formats the language code to lowercase, script code to titlecase, and region code to uppercase. For example: "EN-us" -> "en-US", "ZH-hant-tw" -> "zh-Hant-TW".
func PrimaryLanguage ¶
PrimaryLanguage returns the most preferred language from the Accept-Language header using a zero-allocation fast path. It simply returns the first valid language tag found without parsing full Q-values or sorting.
func SetContentLanguage ¶
func SetContentLanguage(w http.ResponseWriter, lang string)
SetContentLanguage sets the Content-Language HTTP response header.
func SetVary ¶
func SetVary(w http.ResponseWriter)
SetVary adds Accept-Language to the Vary HTTP response header.
Types ¶
type Language ¶
type Language struct {
Tag string // The full language tag (e.g., "en-US")
Language string // The base language (e.g., "en")
Script string // The script (e.g., "Hant")
Region string // The region (e.g., "US")
Quality float64 // The quality value (q-factor), default is 1.0
}
Language represents a parsed language tag and its associated quality value.
func FromRequest ¶
FromRequest parses the Accept-Language header from the request and returns the highest quality Language.
func Languages ¶
Languages extracts and parses the language from the request, checking Accept-Language, Language, and Lang headers.
func Parse ¶
Parse parses the Accept-Language header in lenient mode, preserving the original order.
func ParseRaw ¶
ParseRaw parses the Accept-Language header and returns the languages in the exact order they appeared. It ignores malformed segments (lenient mode).
func ParseSorted ¶
ParseSorted parses the Accept-Language header, removes invalid segments, and returns the valid languages sorted by quality (descending).
func ParseStrict ¶
ParseStrict parses the Accept-Language header and returns an error if any segment is malformed.
type MatchStrategy ¶
type MatchStrategy int
MatchStrategy defines how parsed languages are matched against supported languages.
const ( // Exact requires an exact match of the language tag. Exact MatchStrategy = iota // Basic matches based on the base language only (e.g., en-US matches en). Basic // Lookup uses standard fallback lookup (e.g., zh-Hant-TW -> zh-Hant -> zh). Lookup // Fallback is an alias for Lookup. Fallback // PreferRegion prefers matching the same region if possible, falls back to Lookup. PreferRegion )
type ParseError ¶
ParseError describes an error that occurred while parsing an Accept-Language header.
func (*ParseError) Error ¶
func (e *ParseError) Error() string
Error implements the error interface.
type Resolution ¶
type Resolution struct {
Tag string
Language string
Script string
Region string
Source Source
Quality float64
Matched string
}
Resolution represents the result of resolving a locale.
type Resolver ¶
type Resolver struct {
// contains filtered or unexported fields
}
Resolver resolves the best language for an HTTP request or header.
func NewResolver ¶
func NewResolver(opts ...ResolverOption) *Resolver
NewResolver creates a new Resolver with the given options.
func (*Resolver) Resolve ¶
func (r *Resolver) Resolve(header string) Resolution
Resolve resolves the best matching language for an Accept-Language header string.
func (*Resolver) ResolveRequest ¶
func (r *Resolver) ResolveRequest(req *http.Request) Resolution
ResolveRequest resolves the best matching language for an HTTP request based on the configured extractors (URL, Query, Cookie, Header) and their priority.
type ResolverOption ¶
type ResolverOption func(*Resolver)
ResolverOption configures the Resolver.
func WithCookie ¶
func WithCookie(name string) ResolverOption
WithCookie enables extracting the language from a cookie.
func WithDefault ¶
func WithDefault(lang string) ResolverOption
WithDefault sets the default language to use if no match is found.
func WithFallback ¶
func WithFallback(tag, fallback string) ResolverOption
WithFallback adds a custom fallback mapping.
func WithHeader ¶
func WithHeader(headers ...string) ResolverOption
WithHeader enables extracting the language from HTTP headers. If no headers are specified, it defaults to "Accept-Language".
func WithQuery ¶
func WithQuery(param string) ResolverOption
WithQuery enables extracting the language from a query parameter.
func WithSupported ¶
func WithSupported(langs ...string) ResolverOption
WithSupported sets the list of supported languages.
func WithURL ¶
func WithURL() ResolverOption
WithURL enables extracting the language from the first path segment of the URL (e.g. /en/products).