# Internationalization

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

## Choose explicit locales {#overview}

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 {#example}

```go
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 {#fallback}

- A supported first path segment wins: `/fr-ca/hello` selects `fr-ca`, regardless of browser preferences. `/french` does not match `fr`.
- With `Negotiate: true`, unprefixed paths inspect `Accept-Language`, highest quality first. Equal weights keep header order. An exact supported tag or its supported parent is selected; no sibling region is guessed. `fr-CH` can match `fr`.
- Malformed preferences and zero-quality entries are ignored. A wildcard selects the default. When nothing matches, the default is served; this is a preference resolver and does not produce a 406 response.
- Without negotiation, unprefixed paths always select the default. Unknown prefixes are ordinary path segments, not automatically rejected; register only supported routes when you want a 404.
- `Text("fr-ca", "welcome")` tries `fr-ca`, then `fr`, then the default catalog. Missing keys return the key. An explicitly empty translation stays empty.

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 {#urls}

```go
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 {#publishing}

```go
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](https://developers.google.com/search/docs/specialty/international/localized-versions#sitemap).

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 {#next}

The [publishing guide](/docs/publishing) covers sitemap and feed handlers. Use [typed content collections](/docs/content-v2) to model locale fields and translation relations, and [smart prefetching](/docs/prefetch) to warm explicit localized links.
