Localization
suggest changeLocalization (l10n) means showing your program's text, numbers and other data the way users expect in their language and region. Internationalization (i18n) is the work you do in code so that localization is possible.
The Go standard library doesn't do localization. fmt.Printf("%d", 1234567) always prints 1234567, and strings.ToUpper doesn't know about Turkish. The semi-official golang.org/x/text module, maintained by the Go team, fills the gap:
languageparses language tags and picks the best supported language for a usermessageis a localized replacement forfmtwith translation catalogsfeature/pluralselects the right plural formnumberandcurrencyformat numbers, percentages and moneycollatesorts strings in a language-aware waycasesdoes language-aware upper, lower and title caselanguage/displaygives the names of languages and regions
Add it to your module with:
go get golang.org/x/text@latest
The examples use golang.org/x/text v0.43.0 and Go 1.27.
Language tags
A language is identified by a BCP 47 tag such as en, en-US, pt-BR or sr-Latn. A tag has a base language, plus an optional script and region. language.Tag represents a parsed tag:
package main
import (
"fmt"
"golang.org/x/text/language"
)
func main() {
tag := language.MustParse("pt-BR")
base, _ := tag.Base()
region, _ := tag.Region()
fmt.Println(tag, base, region)
// Parse is lenient about case and separators
t, err := language.Parse("EN_us")
fmt.Println(t, err)
_, err = language.Parse("not a tag!")
fmt.Println(err)
// predefined tags
fmt.Println(language.German, language.SimplifiedChinese, language.BrazilianPortuguese)
// script is inferred when not given
script, conf := language.MustParse("sr").Script()
fmt.Println(script, conf)
script, conf = language.MustParse("sr-Latn").Script()
fmt.Println(script, conf)
}
pt-BR pt BR
en-US <nil>
language: tag is not well-formed
de zh-Hans pt-BR
Cyrl Low
Latn Exact
Base, Script and Region return a confidence value together with the result. If the tag doesn't say, the package guesses from CLDR data: Serbian is written in Cyrillic by default, so sr gives Cyrl with Low confidence.
Use language.MustParse for constants in your code and language.Parse for user input.
Picking the user's language
You support a fixed set of languages. Users ask for theirs, usually through the browser's Accept-Language header. language.Matcher finds the best match between the two:
package main
import (
"fmt"
"golang.org/x/text/language"
)
// languages the app has translations for; the first is the fallback
var supported = []language.Tag{
language.English,
language.German,
language.French,
language.BrazilianPortuguese,
}
var matcher = language.NewMatcher(supported)
func main() {
headers := []string{
"de-AT,en;q=0.8",
"fr, en;q=0.8",
"pt-PT,pt;q=0.9",
"ja-JP,ja;q=0.9",
"",
}
for _, h := range headers {
tag, idx := language.MatchStrings(matcher, h)
fmt.Printf("%-18q -> %-16v %v\n", h, tag, supported[idx])
}
tags, q, err := language.ParseAcceptLanguage("da, en-GB;q=0.8, en;q=0.7")
fmt.Println(tags, q, err)
tag, idx, conf := matcher.Match(tags...)
fmt.Println(tag, idx, conf)
}
"de-AT,en;q=0.8" -> de-u-rg-atzzzz de
"fr, en;q=0.8" -> fr fr
"pt-PT,pt;q=0.9" -> pt-BR pt-BR
"ja-JP,ja;q=0.9" -> en en
"" -> en en
[da en-GB en] [1 0.8 0.7] <nil>
en 0 Exact
Things to notice:
MatchStringstakes any number of strings. Each one can be a single tag or a wholeAccept-Languagevalue. Invalid strings are skipped, so passing an empty cookie value is fine.- Portuguese from Portugal (
pt-PT) is matched to our Brazilian Portuguese. That beats falling back to English. - When nothing matches, you get the first supported tag, so put your default language first.
- The returned tag can carry extra information.
de-u-rg-atzzzzmeans "German, with Austria as the region". Use it for formatting (numbers, currency), so the user's regional preferences are kept. Use the index intosupportedto choose a translation file or to set aContent-Languageheader.
Localized number formatting
message.Printer has the same methods as package fmt: Printf, Sprintf, Fprintf, Println and so on. The difference is that it formats numbers for its language:
package main
import (
"golang.org/x/text/currency"
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/number"
)
func main() {
for _, tag := range []language.Tag{language.AmericanEnglish, language.German, language.French, language.Hindi} {
p := message.NewPrinter(tag)
p.Printf("%-6v %d | %.2f | %v | %v\n", tag, 1234567, 1234567.891,
number.Percent(0.256), currency.EUR.Amount(1234.5))
}
p := message.NewPrinter(language.English)
p.Printf("%v\n", number.Decimal(3.14159, number.MaxFractionDigits(2)))
p.Printf("%v\n", number.Decimal(42, number.MinIntegerDigits(5)))
p.Printf("%v\n", number.Decimal(1234567, number.NoSeparator()))
p.Printf("%v\n", currency.Symbol(currency.USD.Amount(9.99)))
p.Printf("%v\n", currency.ISO(currency.JPY.Amount(1500)))
s := p.Sprintf("%d items", 10000)
p.Println(s)
}
en-US 1,234,567 | 1,234,567.89 | 26% | EUR 1,234.50
de 1.234.567 | 1.234.567,89 | 26 % | EUR 1.234,50
fr 1 234 567 | 1 234 567,89 | 26 % | EUR 1 234,50
hi 12,34,567 | 12,34,567.89 | 26% | EUR 1,234.50
3.14
00,042
1234567
$ 9.99
JPY 1,500
10,000 items
The group separator is , in English and . in German. Hindi groups digits as lakhs and crores (12,34,567). In French (and Polish) the separator is a non-breaking space, U+00A0, not a regular space. Keep that in mind if you compare formatted output in tests or try to parse it back.
number.Decimal, number.Percent and friends take options for the number of digits and grouping. The currency package knows ISO 4217 codes and the usual number of decimal digits for each currency. Its output is basic: the code or symbol always comes first, even in languages that put it after the number. If you need exact local currency formatting for invoices, check the output for every language you support.
Note that p.Println(s) prints a string that is already formatted unchanged. Only numbers passed as arguments are localized.
Translating messages with a catalog
A catalog maps a message key to its translation in each language. The key is usually the English text itself. catalog.Builder lets you fill a catalog in code:
package main
import (
"fmt"
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/message/catalog"
)
func main() {
cat := catalog.NewBuilder()
cat.SetString(language.English, "Hello, %s!", "Hello, %s!")
cat.SetString(language.German, "Hello, %s!", "Hallo, %s!")
cat.SetString(language.Polish, "Hello, %s!", "Cześć, %s!")
// argument order can differ between languages
cat.SetString(language.English, "%s has %d new messages", "%[1]s has %[2]d new messages")
cat.SetString(language.German, "%s has %d new messages", "%[2]d neue Nachrichten für %[1]s")
for _, tag := range []language.Tag{language.English, language.German, language.Polish, language.French} {
p := message.NewPrinter(tag, message.Catalog(cat))
p.Printf("Hello, %s!", "Anna")
fmt.Print(" | ")
p.Printf("%s has %d new messages", "Anna", 1200)
fmt.Println()
}
}
Hello, Anna! | Anna has 1,200 new messages
Hallo, Anna! | 1.200 neue Nachrichten für Anna
Cześć, Anna! | Anna has 1 200 new messages
Hello, Anna! | Anna has 1 200 new messages
The printer looks up the format string in the catalog. If there's no translation, the key is used as the format, which is why it's handy for the key to be the English text.
Translators often need to reorder arguments. Use explicit argument indexes like %[2]d (see Format text) so the German sentence can put the number first.
Look at the last two lines. Polish has no translation for the second message and French has no translations at all, so the English key is printed. The numbers are still formatted for the printer's language, with a non-breaking space as the group separator. A missing translation doesn't cause an error, so check that every key has a translation for every language you support, for example in a test.
For a quick start you can also call the package-level message.SetString(tag, key, msg), which fills message.DefaultCatalog.
Plurals
"1 files" looks sloppy, and if n == 1 only works for English. Languages have different plural rules. Polish uses one form for 1, another for 2-4, 22-24, 32-34 and so on, and a third for 5-21, 25-31 etc. plural.Selectf picks the form based on CLDR plural rules:
package main
import (
"golang.org/x/text/feature/plural"
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/message/catalog"
)
func main() {
cat := catalog.NewBuilder()
key := "You have %d files"
cat.Set(language.English, key, plural.Selectf(1, "%d",
"=0", "You have no files",
plural.One, "You have %d file",
plural.Other, "You have %d files",
))
// Polish has three plural forms: one, few and many
cat.Set(language.Polish, key, plural.Selectf(1, "%d",
"=0", "Nie masz plików",
plural.One, "Masz %d plik",
plural.Few, "Masz %d pliki",
plural.Many, "Masz %d plików",
))
en := message.NewPrinter(language.English, message.Catalog(cat))
pl := message.NewPrinter(language.Polish, message.Catalog(cat))
for _, n := range []int{0, 1, 2, 5, 22, 25, 1000} {
en.Printf(key, n)
en.Print(" | ")
pl.Printf(key, n)
en.Println()
}
}
You have no files | Nie masz plików
You have 1 file | Masz 1 plik
You have 2 files | Masz 2 pliki
You have 5 files | Masz 5 plików
You have 22 files | Masz 22 pliki
You have 25 files | Masz 25 plików
You have 1,000 files | Masz 1 000 plików
plural.Selectf(1, "%d", ...) says: look at argument 1, formatted as %d, and choose a case. The cases are pairs of selector and message. Selectors are the CLDR categories plural.Zero, One, Two, Few, Many and Other, or an exact value like "=0". Exact values are checked first. Other is the fallback and should always be present.
The formatting (%d) matters for languages where 1.0 and 1 take different forms, so use the same verb you use in the message.
Translations in files with go-i18n
x/text is good for formatting, but filling catalogs in Go code doesn't scale to many languages and translators who don't write Go. x/text has a gotext tool (golang.org/x/text/cmd/gotext) that extracts messages from your code into JSON files and generates a catalog, but most projects use github.com/nicksnyder/go-i18n. It loads messages from JSON, TOML or YAML files, handles plurals and uses text/template syntax for placeholders.
go get github.com/nicksnyder/go-i18n/v2@latest
Put one file per language in locales/. locales/active.en.json:
{
"Welcome": "Welcome, {{.Name}}!",
"Unread": {
"one": "You have {{.Count}} unread message",
"other": "You have {{.Count}} unread messages"
}
}
locales/active.pl.json:
{
"Welcome": "Witaj, {{.Name}}!",
"Unread": {
"one": "Masz {{.Count}} nieprzeczytaną wiadomość",
"few": "Masz {{.Count}} nieprzeczytane wiadomości",
"many": "Masz {{.Count}} nieprzeczytanych wiadomości",
"other": "Masz {{.Count}} nieprzeczytanej wiadomości"
}
}
The language comes from the file name (active.pl.json is Polish). Embed the files into the binary with //go:embed so you don't have to ship them separately:
package main
import (
"embed"
"encoding/json"
"fmt"
"github.com/nicksnyder/go-i18n/v2/i18n"
"golang.org/x/text/language"
)
//go:embed locales/*.json
var localeFS embed.FS
func newBundle() *i18n.Bundle {
bundle := i18n.NewBundle(language.English)
bundle.RegisterUnmarshalFunc("json", json.Unmarshal)
for _, name := range []string{"active.en.json", "active.pl.json"} {
if _, err := bundle.LoadMessageFileFS(localeFS, "locales/"+name); err != nil {
panic(err)
}
}
return bundle
}
func main() {
bundle := newBundle()
// Localizer picks the best language from a list of preferences,
// e.g. a user setting followed by the Accept-Language header
for _, langs := range [][]string{{"pl"}, {"en-US"}, {"fr", "pl-PL;q=0.8"}, {"ja"}} {
loc := i18n.NewLocalizer(bundle, langs...)
welcome := loc.MustLocalize(&i18n.LocalizeConfig{
MessageID: "Welcome",
TemplateData: map[string]string{"Name": "Ola"},
})
fmt.Printf("%v: %s\n", langs, welcome)
for _, n := range []int{1, 3, 5} {
msg := loc.MustLocalize(&i18n.LocalizeConfig{
MessageID: "Unread",
PluralCount: n,
TemplateData: map[string]int{"Count": n},
})
fmt.Println(" ", msg)
}
}
// a missing message returns an error you can handle
_, err := i18n.NewLocalizer(bundle, "en").Localize(&i18n.LocalizeConfig{MessageID: "Goodbye"})
fmt.Println(err)
// DefaultMessage provides the source-language text inline
goodbye := &i18n.Message{ID: "Goodbye", Other: "Goodbye, {{.Name}}!"}
for _, lang := range []string{"en", "pl"} {
loc := i18n.NewLocalizer(bundle, lang)
s, err := loc.Localize(&i18n.LocalizeConfig{
DefaultMessage: goodbye,
TemplateData: map[string]string{"Name": "Ola"},
})
fmt.Printf("%s: %q err: %v\n", lang, s, err)
}
}
[pl]: Witaj, Ola!
Masz 1 nieprzeczytaną wiadomość
Masz 3 nieprzeczytane wiadomości
Masz 5 nieprzeczytanych wiadomości
[en-US]: Welcome, Ola!
You have 1 unread message
You have 3 unread messages
You have 5 unread messages
[fr pl-PL;q=0.8]: Witaj, Ola!
Masz 1 nieprzeczytaną wiadomość
Masz 3 nieprzeczytane wiadomości
Masz 5 nieprzeczytanych wiadomości
[ja]: Welcome, Ola!
You have 1 unread message
You have 3 unread messages
You have 5 unread messages
message "Goodbye" not found in language "en"
en: "Goodbye, Ola!" err: <nil>
pl: "Goodbye, Ola!" err: message "Goodbye" not found in language "pl"
How it works:
- A
Bundleholds all messages. Create it once at startup and share it. The language passed toNewBundleis the default. - A
Localizeris cheap to create. Make one per request from the user's preferences, most important first. It understandsAccept-Languagesyntax. PluralCountselects the plural form, andTemplateDatafills the placeholders. They are separate, so pass the count in both.MustLocalizepanics if the message is missing. UseLocalizein request handlers. When a translation is missing, it returns the default message together with an error. You can log the error and still show the text.
DefaultMessage lets you write the English text next to the code that uses it. The goi18n command (go install github.com/nicksnyder/go-i18n/v2/goi18n@latest) can extract those messages into a file for translators and merge translated files back.
Localization in an HTTP server
In a web app you pick the language once per request, in middleware, and store the printer in the request context. An explicit choice saved in a cookie wins over Accept-Language:
package main
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"golang.org/x/text/language"
"golang.org/x/text/message"
"golang.org/x/text/message/catalog"
)
var supported = []language.Tag{language.English, language.German, language.Polish}
var matcher = language.NewMatcher(supported)
var cat = catalog.NewBuilder()
func init() {
cat.SetString(language.German, "Hello! You have %d points.", "Hallo! Sie haben %d Punkte.")
cat.SetString(language.Polish, "Hello! You have %d points.", "Cześć! Masz %d punktów.")
}
type ctxKey struct{}
// withLocale picks a language from the "lang" cookie (explicit user choice)
// falling back to the Accept-Language header
func withLocale(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var cookieLang string
if c, err := r.Cookie("lang"); err == nil {
cookieLang = c.Value
}
tag, idx := language.MatchStrings(matcher, cookieLang, r.Header.Get("Accept-Language"))
p := message.NewPrinter(tag, message.Catalog(cat))
w.Header().Set("Content-Language", supported[idx].String())
ctx := context.WithValue(r.Context(), ctxKey{}, p)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func printer(r *http.Request) *message.Printer {
return r.Context().Value(ctxKey{}).(*message.Printer)
}
func handleHome(w http.ResponseWriter, r *http.Request) {
printer(r).Fprintf(w, "Hello! You have %d points.", 12500)
}
func main() {
srv := httptest.NewServer(withLocale(http.HandlerFunc(handleHome)))
defer srv.Close()
get := func(acceptLang, cookie string) {
req, _ := http.NewRequest("GET", srv.URL, nil)
req.Header.Set("Accept-Language", acceptLang)
if cookie != "" {
req.AddCookie(&http.Cookie{Name: "lang", Value: cookie})
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Printf("%-22q cookie=%-3q -> [%s] %s\n", acceptLang, cookie, resp.Header.Get("Content-Language"), body)
}
get("de-DE,de;q=0.9", "")
get("pl,en;q=0.5", "")
get("es-ES", "")
get("de-DE,de;q=0.9", "pl")
}
"de-DE,de;q=0.9" cookie="" -> [de] Hallo! Sie haben 12.500 Punkte.
"pl,en;q=0.5" cookie="" -> [pl] Cześć! Masz 12 500 punktów.
"es-ES" cookie="" -> [en] Hello! You have 12,500 points.
"de-DE,de;q=0.9" cookie="pl" -> [pl] Cześć! Masz 12 500 punktów.
English has no catalog entries here, so for English the key itself is the text. A real app would use plural.Selectf for "points", since "1 points" is wrong.
With html/template, register a function that calls the printer, or pass already translated strings as template data.
Language-aware case conversion
strings.ToUpper and strings.ToLower use language-independent Unicode rules (see Convert to lower case or upper case). Some languages need special rules. Package cases handles them:
package main
import (
"fmt"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
func main() {
s := "istanbul ırmak"
fmt.Println(strings.ToUpper(s))
fmt.Println(cases.Upper(language.Turkish).String(s))
fmt.Println(cases.Title(language.English).String("the quick brown fox"))
fmt.Println(cases.Title(language.Dutch).String("ijsland is mooi"))
// German sharp s
fmt.Println(strings.ToUpper("straße"), cases.Upper(language.German).String("straße"))
// case-insensitive comparison: Fold is better than ToLower
fold := cases.Fold()
fmt.Println(fold.String("Straße") == fold.String("STRASSE"))
fmt.Println(strings.EqualFold("Straße", "STRASSE"))
}
ISTANBUL IRMAK
İSTANBUL IRMAK
The Quick Brown Fox
IJsland Is Mooi
STRAßE STRASSE
true
false
In Turkish, the upper case of i is İ (dotted capital I), not I. Dutch capitalizes the ij digraph together. In German ß becomes SS in upper case.
cases.Title replaces the deprecated strings.Title. A cases.Caser keeps state, so don't share one between goroutines. Creating one is cheap.
cases.Fold does full case folding, which also handles ß vs ss. strings.EqualFold only does simple folding, one rune to one rune.
Sorting strings for humans
slices.Sort on strings compares bytes. Upper case letters come before all lower case letters, and accented letters come after z. Users expect alphabetical order, and that order depends on the language. Package collate implements the Unicode Collation Algorithm with per-language rules:
package main
import (
"fmt"
"slices"
"golang.org/x/text/collate"
"golang.org/x/text/language"
)
func main() {
words := []string{"zebra", "Äpfel", "apple", "Zürich", "öl", "ostrich", "Ångström"}
plain := slices.Clone(words)
slices.Sort(plain)
fmt.Println("byte order:", plain)
for _, tag := range []language.Tag{language.English, language.German, language.Swedish} {
w := slices.Clone(words)
collate.New(tag).SortStrings(w)
fmt.Printf("%-10v %v\n", tag.String()+":", w)
}
c := collate.New(language.English, collate.IgnoreCase, collate.IgnoreDiacritics)
fmt.Println(c.CompareString("Resume", "résumé"))
fmt.Println(collate.New(language.English).CompareString("Resume", "résumé"))
// numeric option sorts digits by value
files := []string{"file10.txt", "file2.txt", "file1.txt"}
collate.New(language.English, collate.Numeric).SortStrings(files)
fmt.Println(files)
}
byte order: [Zürich apple ostrich zebra Äpfel Ångström öl]
en: [Ångström Äpfel apple öl ostrich zebra Zürich]
de: [Ångström Äpfel apple öl ostrich zebra Zürich]
sv: [apple ostrich zebra Zürich Ångström Äpfel öl]
0
-1
[file1.txt file2.txt file10.txt]
In English and German, Ä sorts with a and ö with o. In Swedish, å, ä and ö are separate letters that come after z.
CompareString returns -1, 0 or 1 like strings.Compare, so you can use it with slices.SortFunc. With IgnoreCase and IgnoreDiacritics, "Resume" and "résumé" are equal, which is useful for search. collate.Numeric gives the "natural" order that file managers use.
A Collator keeps internal buffers, so it's not safe for concurrent use either. Create one per goroutine or protect it with a mutex.
Names of languages and regions
A language picker should show each language's name in that language, so a German user can find "Deutsch" even if the page is in Japanese. Package display has the names from CLDR:
package main
import (
"fmt"
"golang.org/x/text/language"
"golang.org/x/text/language/display"
)
func main() {
tags := []language.Tag{language.English, language.German, language.Japanese, language.MustParse("pt-BR")}
en := display.English.Tags()
de := display.German.Tags()
for _, t := range tags {
fmt.Printf("%-6v %-24s %-26s %s\n", t, en.Name(t), de.Name(t), display.Self.Name(t))
}
fmt.Println(display.English.Regions().Name(language.MustParseRegion("CH")))
fmt.Println(display.French.Regions().Name(language.MustParseRegion("CH")))
}
en English Englisch English
de German Deutsch Deutsch
ja Japanese Japanisch 日本語
pt-BR Brazilian Portuguese Brasilianisches Portugiesisch português
Switzerland
Suisse
display.Self names each language in itself. The display package includes name tables for all languages and adds a couple of megabytes to your binary (about 2.4 MB in this example). If you only need a language picker, a small hand-written map is usually enough.
Dates and times
x/text doesn't format dates. The time package always uses English month and day names (see Format time). Options:
- use a numeric format that works everywhere, like ISO 8601
2026-10-17 - put month and day names in your translation files and build the date yourself
- use a third-party package such as
github.com/goodsign/monday, which translates the names intime.Formatoutput
Also store and send times in UTC, and convert to the user's time zone with time.LoadLocation only when showing them.
Practical advice
- Don't build sentences by joining pieces:
"Deleted " + n + " " + nouncan't be translated. Translate whole sentences with placeholders. - Give translators context. The same English word ("Open", "Save") may need different translations as a button label and as a status.
- Expect translated text to be longer. German is often 30% longer than English, so leave room in the UI.
- Format numbers and amounts with the printer even in otherwise untranslated output, like reports and CSV exports meant for people. Machine-readable output (JSON, logs, config files) should stay language-neutral, so use plain
fmtandstrconvthere. - Test with a language that has complex plurals (Polish, Russian, Arabic) and with a long one (German) early, not after the UI is finished.
Summary
- the standard library doesn't localize; use
golang.org/x/text language.Parseparses BCP 47 tags;language.NewMatcherplusMatchStringspicks the best supported language from cookies andAccept-Languagemessage.NewPrinter(tag)works likefmtand formats numbers for the language;numberandcurrencyadd percentages, digit options and moneycatalog.Builderandmessage.Catalogtranslate format strings; use%[n]indexes so translators can reorder argumentsplural.Selectfpicks plural forms using CLDR rules- for translation files use
go-i18n: JSON/TOML/YAML messages, templates, plurals andgo:embed casesdoes language-aware upper, lower and title case and full case foldingcollatesorts and compares strings the way users expect, with options to ignore case and accents and to sort numbers by valuedisplaygives names of languages and regions- dates need your own translations or a third-party package