Documentation / Internationalization

Internationalization

Resolve request locales, generate localized URLs, look up translated messages, and publish language metadata in sitemaps and feeds.

Choose explicit locales

The hyperchi/i18n package provides an immutable bundle of supported locales and plain-text message catalogs. Create it once during startup. Locale-prefixed paths take priority; optional browser-language negotiation applies only when the path has no supported prefix. Otherwise, the configured default applies.

Every generated URL includes a locale prefix, including the default locale. Route registration stays explicit: the middleware sets request context and response metadata without rewriting routes, redirecting visitors, or setting cookies.

Configure the application

import "github.com/regiellis/hyperchi/hyperchi/i18n"

languages, err := i18n.New(i18n.Config{
    Default: "en",
    Locales: []string{"en", "fr", "fr-ca"},
    Catalogs: map[string]map[string]string{
        "en": {"welcome": "Welcome", "contact": "Contact us"},
        "fr": {"welcome": "Bienvenue"},
        "fr-ca": {"contact": "Contactez-nous"},
    },
})
if err != nil {
    return err
}
app.UseGlobal(languages.Middleware)

// Register only the supported prefixes, leaving unknown locales as 404s.
for _, locale := range languages.Locales() {
    app.Get("/"+locale+"/hello", func(c *hyperchi.Context) error {
        return c.Text(languages.Text(c.Locale(), "welcome"))
    })
}

c.Locale() is empty when middleware is absent. Plain net/http handlers can use i18n.Locale(r.Context()). The middleware sets Content-Language; override it if a handler serves content in another language. Apply middleware to the relevant route group when assets and API responses should not carry language metadata.

Pass the locale and translated strings as normal template data, including the page's <html lang="...">. Keep catalog strings as strings so html/template escapes them. The bundle copies input maps and slices and is safe to share across concurrent requests. Build a replacement bundle to change catalogs.

Resolution and fallback

Locales are normalized to lowercase and validated for basic language-tag syntax, not against the IANA registry. Aliases and likely subtags are not inferred. Catalogs support plain strings; pluralization, interpolation, date/number formatting, and translation-file loaders are left to application code. Catalog fallback does not make missing translated pages exist.

Negotiated responses add Vary: Accept-Language. Preserve this value if application code replaces the Vary header. Explicit locale paths do not vary by browser language. Use explicit localized URLs for public caches, canonical links, and prefetch links so their language stays predictable.

Localized links

french, err := languages.Path("fr", "/en/articles?sort=new#latest")
// french == "/fr/articles?sort=new#latest"
if err != nil {
    return err
}

Path adds or replaces a supported prefix. It preserves escaped bytes, trailing slashes, query strings, and fragments. Only root-relative URLs are accepted; external URLs, dot segments, and encoded separators return errors. An unsupported target locale also returns an error. It does not translate slugs or verify that a destination page exists. Keep a mapping of translated content IDs to their real paths when slugs differ between languages.

Localized publishing

alternates := []publishing.Alternate{
    {Language: "en", URL: "https://example.com/en/about"},
    {Language: "fr", URL: "https://example.com/fr/a-propos"},
    {Language: "x-default", URL: "https://example.com/en/about"},
}
sitemap, err := publishing.Sitemap([]publishing.SitemapEntry{
    {URL: "https://example.com/en/about", Alternates: alternates},
    {URL: "https://example.com/fr/a-propos", Alternates: alternates},
})
if err != nil {
    return err
}
_ = sitemap // Serve sitemap.Handler(), or write sitemap.Bytes().

Alternates become XHTML link elements with rel="alternate", hreflang, and href. Provide the same reciprocal set on every translated page, including itself. The generator validates unique language tags and absolute HTTP(S) links; it does not discover translations or enforce reciprocity. Alternate links may point to other origins, while the sitemap's primary page URLs must still share an origin. See Google's localized sitemap guidance.

Set publishing.Feed.Language to emit RSS channel language and Atom xml:lang. It is optional, so existing feeds retain their output. Generate a separate feed for each language and include only that language's public entries. Feed entry summaries inherit the feed language.

Next steps

The publishing guide covers sitemap and feed handlers. Use typed content collections to model locale fields and translation relations, and smart prefetching to warm explicit localized links.