### Install and Use goi18n Command Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Install the goi18n command-line tool globally using `go install`. The command helps manage translation files. ```bash go install -v github.com/nicksnyder/go-i18n/v2/goi18n@latest goi18n -help ``` -------------------------------- ### Run go-i18n Example Source: https://github.com/nicksnyder/go-i18n/blob/main/example/README.md Execute the example project using the go run command. Open the specified URL in your web browser to view the output. ```bash go run main.go ``` -------------------------------- ### Install goi18n CLI Tool Source: https://context7.com/nicksnyder/go-i18n/llms.txt Command to install the `goi18n` command-line tool using `go install`. This tool is used for extracting messages from Go source code and merging translation files. ```bash # Install the tool go install github.com/nicksnyder/go-i18n/v2/goi18n@latest ``` -------------------------------- ### Customize Locale via Query Parameters Source: https://github.com/nicksnyder/go-i18n/blob/main/example/README.md Access the example application with custom template data and locale settings by appending query parameters to the URL. The 'lang' parameter specifies the desired locale. ```http http://localhost:8080/?name=Nick&unreadEmailCount=2 ``` ```http http://localhost:8080/?name=Nick&unreadEmailCount=2&lang=es ``` -------------------------------- ### Merge Translations with goi18n Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Merge existing translation files with new ones to update translations. This example shows populating a new language file. ```toml # translate.es.toml [HelloPerson] hash = "sha1-5b49bfdad81fedaeefb224b0ffc2acc58b09cff5" other = "Hello {{.Name}}" ``` ```toml # active.es.toml [HelloPerson] hash = "sha1-5b49bfdad81fedaeefb224b0ffc2acc58b09cff5" other = "Hola {{.Name}}" ``` -------------------------------- ### Create and Initialize Bundle Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Create a new i18n bundle for the lifetime of your application, specifying the default language. ```go bundle := i18n.NewBundle(language.English) ``` -------------------------------- ### Create a Localizer Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Create a localizer instance for a given request, using the application's bundle and language preferences derived from request headers or form values. ```go func(w http.ResponseWriter, r *http.Request) { lang := r.FormValue("lang") accept := r.Header.Get("Accept-Language") localizer := i18n.NewLocalizer(bundle, lang, accept) } ``` -------------------------------- ### Create and Initialize Translation Bundle Source: https://context7.com/nicksnyder/go-i18n/llms.txt Initializes a new translation bundle with a default language and registers a TOML unmarshal function. It then loads translations from an active TOML file and lists all loaded language tags. ```go import ( "github.com/BurntSushi/toml" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) // Load translations from disk if _, err := bundle.LoadMessageFile("active.es.toml"); err != nil { log.Fatalf("failed to load translations: %v", err) } // List all loaded language tags for _, tag := range bundle.LanguageTags() { fmt.Println(tag) // e.g. "en", "es" } ``` -------------------------------- ### Load Translations from File Path Source: https://context7.com/nicksnyder/go-i18n/llms.txt Demonstrates loading translations from a TOML file using `LoadMessageFile`, which returns an error for graceful handling. It also shows `MustLoadMessageFile` which panics on error, suitable for critical initialization. ```go bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) // Returns an error — handle gracefully mf, err := bundle.LoadMessageFile("active.es.toml") if err != nil { log.Fatalf("failed to load: %v", err) } fmt.Printf("Loaded %d messages for %s\n", len(mf.Messages), mf.Tag) // Panics on failure — use during app startup bundle.MustLoadMessageFile("active.fr.toml") ``` -------------------------------- ### Create Request-Scoped Localizer with i18n.NewLocalizer Source: https://context7.com/nicksnyder/go-i18n/llms.txt `NewLocalizer` creates a `Localizer` bound to a bundle and a prioritized list of language preferences. It accepts raw BCP 47 language tags and `Accept-Language` header values. Language matching falls back gracefully through the preference list to the bundle's default language. ```go func handleRequest(w http.ResponseWriter, r *http.Request) { // Combine explicit lang param with Accept-Language header lang := r.FormValue("lang") accept := r.Header.Get("Accept-Language") localizer := i18n.NewLocalizer(bundle, lang, accept) // localizer is now ready for this request's language context _ = localizer } // For tests or background jobs, pass tags directly localizer := i18n.NewLocalizer(bundle, "es-MX", "es", "en") ``` -------------------------------- ### Import go-i18n Package Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Import the necessary i18n package for localization functionalities. ```go import "github.com/nicksnyder/go-i18n/v2/i18n" ``` -------------------------------- ### Load Message Files (Standard) Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Register a function to unmarshal message files and then load a message file into the bundle. ```go bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) bundle.LoadMessageFile("es.toml") ``` -------------------------------- ### List Loaded Languages from Bundle in Go Source: https://context7.com/nicksnyder/go-i18n/llms.txt Initializes an `i18n.Bundle`, registers a TOML unmarshal function, loads message files, and then iterates through `bundle.LanguageTags()` to print all loaded language tags. Useful for UI language selection or validation. ```go bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) bundle.MustLoadMessageFile("active.es.toml") bundle.MustLoadMessageFile("active.fr.toml") for _, tag := range bundle.LanguageTags() { fmt.Println(tag) } // en // es // fr ``` -------------------------------- ### Configure Localization Call with Template Data and Custom Functions in Go Source: https://context7.com/nicksnyder/go-i18n/llms.txt Demonstrates the use of `i18n.LocalizeConfig` for localization calls, including `MessageID`, `DefaultMessage`, `TemplateData`, `PluralCount`, and custom template `Funcs`. Shows error handling for `localizer.Localize`. ```go // All fields demonstrated msg, err := localizer.Localize(&i18n.LocalizeConfig{ // MessageID is used when the message is loaded from a file, not inline MessageID: "WelcomeBack", // DefaultMessage is used when MessageID is not found (or as the primary for default lang) DefaultMessage: &i18n.Message{ ID: "WelcomeBack", Other: "Welcome back, {{.Name}}! You have {{.Count}} notifications.", }, // TemplateData is passed to text/template execution TemplateData: map[string]interface{}{ "Name": "Alice", "Count": 7, }, // PluralCount selects the plural form (One/Other/etc.) and auto-sets .PluralCount in template PluralCount: 7, // Funcs adds custom template functions Funcs: template.FuncMap{ "upper": strings.ToUpper, }, }) if err != nil { log.Printf("localization error: %v", err) } fmt.Println(msg) // Welcome back, Alice! You have 7 notifications. ``` -------------------------------- ### Look Up and Render Localized Message with localizer.Localize Source: https://context7.com/nicksnyder/go-i18n/llms.txt The primary lookup method. It accepts a `*LocalizeConfig` which specifies the message ID, optional template data, and an optional plural count. Returns the rendered string and an error (e.g. `*MessageNotFoundErr`). ```go // Simple message lookup by ID (requires message to exist in bundle) msg, err := localizer.Localize(&i18n.LocalizeConfig{ MessageID: "WelcomeMessage", }) if err != nil { // *i18n.MessageNotFoundErr if missing; still returns best-effort string log.Printf("localize error: %v", err) } fmt.Println(msg) // With a default message (no bundle file required for default language) msg, err = localizer.Localize(&i18n.LocalizeConfig{ DefaultMessage: &i18n.Message{ ID: "PersonCats", One: "{{.Name}} has {{.Count}} cat.", Other: "{{.Name}} has {{.Count}} cats.", }, TemplateData: map[string]interface{}{ "Name": "Alice", "Count": 3, }, PluralCount: 3, }) // msg == "Alice has 3 cats." ``` -------------------------------- ### Load Message Files (embed.FS) Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Load message files embedded within the application using `go:embed`. Ensure the unmarshal function is registered first. ```go // If use go:embed //go:embed locale.*.toml var LocaleFS embed.FS bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) bundle.LoadMessageFileFS(LocaleFS, "locale.es.toml") ``` -------------------------------- ### i18n.NewLocalizer Source: https://context7.com/nicksnyder/go-i18n/llms.txt Creates a Localizer bound to a bundle and a prioritized list of language preferences. It accepts raw BCP 47 language tags and Accept-Language header values. Language matching falls back gracefully through the preference list to the bundle's default language. ```APIDOC ## i18n.NewLocalizer ### Description Creates a `Localizer` bound to a bundle and a prioritized list of language preferences. It accepts raw BCP 47 language tags and `Accept-Language` header values. Language matching falls back gracefully through the preference list to the bundle's default language. ### Method `i18n.NewLocalizer(bundle *Bundle, langTags ...string) *Localizer` ### Parameters #### Path Parameters - **bundle** (*Bundle) - Required - The i18n bundle to use for localization. - **langTags** (string) - Required - A variadic list of language tags (BCP 47) or `Accept-Language` header values, defining the language preference order. ### Request Example ```go import ( "net/http" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) // Assuming bundle is an initialized i18n.Bundle var bundle *i18n.Bundle func handleRequest(w http.ResponseWriter, r *http.Request) { // Combine explicit lang param with Accept-Language header lang := r.FormValue("lang") accept := r.Header.Get("Accept-Language") localizer := i18n.NewLocalizer(bundle, lang, accept) // localizer is now ready for this request's language context _ = localizer } // For tests or background jobs, pass tags directly localizer := i18n.NewLocalizer(bundle, "es-MX", "es", "en") ``` ``` -------------------------------- ### Load Translated Message File Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md After translating a message file (e.g., `translate.es.toml` renamed to `active.es.toml`), load it into the i18n bundle. ```go bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) bundle.LoadMessageFile("active.es.toml") ``` -------------------------------- ### Register Messages Programmatically with bundle.AddMessages Source: https://context7.com/nicksnyder/go-i18n/llms.txt Use `bundle.AddMessages` to add `*Message` structs directly to the bundle. This is useful when translations are sourced from a database, remote API, or any non-file storage. ```go bundle := i18n.NewBundle(language.English) err := bundle.AddMessages(language.Spanish, &i18n.Message{ ID: "Greeting", Other: "¡Hola, {{.Name}}!", }, &i18n.Message{ ID: "ItemCount", One: "Tienes {{.PluralCount}} artículo.", Other: "Tienes {{.PluralCount}} artículos.", }, ) if err != nil { log.Fatalf("AddMessages failed: %v", err) } ``` -------------------------------- ### Load Embedded Translations from FS Source: https://context7.com/nicksnyder/go-i18n/llms.txt Loads translations from an embedded filesystem using `LoadMessageFileFS`. This is the recommended approach for embedding translation files directly into the Go binary using `go:embed`. ```go import ( "embed" "github.com/BurntSushi/toml" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) //go:embed locale.*.toml var localeFS embed.FS bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) if _, err := bundle.LoadMessageFileFS(localeFS, "locale.es.toml"); err != nil { log.Fatalf("failed to load embedded translations: %v", err) } ``` -------------------------------- ### bundle.LoadMessageFileFS Source: https://context7.com/nicksnyder/go-i18n/llms.txt Loads translation messages from a file embedded within the application using an `fs.FS` compatible file system. This is the recommended method for embedding translation files directly into the Go binary. ```APIDOC ## bundle.LoadMessageFileFS — Load translations from an `embed.FS` Reads a message file from any `fs.FS` implementation instead of the OS filesystem. This is the recommended approach when embedding translation files into the binary using `go:embed`. ```go import ( "embed" "github.com/BurntSushi/toml" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) //go:embed locale.*.toml var localeFS embed.FS bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) if _, err := bundle.LoadMessageFileFS(localeFS, "locale.es.toml"); err != nil { log.Fatalf("failed to load embedded translations: %v", err) } ``` ``` -------------------------------- ### Localize Directly from a *Message Struct with localizer.LocalizeMessage Source: https://context7.com/nicksnyder/go-i18n/llms.txt A convenience wrapper around `Localize` that accepts a `*Message` directly as the `DefaultMessage`, with no additional configuration needed. ```go catMsg := &i18n.Message{ ID: "Cats", One: "I have {{.PluralCount}} cat.", Other: "I have {{.PluralCount}} cats.", } for _, count := range []int{0, 1, 5} { localizer := i18n.NewLocalizer(bundle, "en") // Note: PluralCount must be set in LocalizeConfig; LocalizeMessage uses "Other" for all counts msg, _ := localizer.Localize(&i18n.LocalizeConfig{ DefaultMessage: catMsg, PluralCount: count, }) fmt.Println(msg) } // I have 0 cats. // I have 1 cat. // I have 5 cats. ``` -------------------------------- ### Look Up Message and Return Matched Tag with localizer.LocalizeWithTag Source: https://context7.com/nicksnyder/go-i18n/llms.txt Same as `Localize` but also returns the `language.Tag` that was actually used to render the message. Useful for logging which language was served or for debugging fallback behavior. ```go msg, tag, err := localizer.LocalizeWithTag(&i18n.LocalizeConfig{ DefaultMessage: &i18n.Message{ ID: "Farewell", Other: "Goodbye!", }, }) if err != nil { // May be a MessageNotFoundErr with a best-effort msg still set log.Printf("warn: %v (served %q in %s)", err, msg, tag) } else { fmt.Printf("Served %q in language %s\n", msg, tag) // e.g. language: en } ``` -------------------------------- ### Localize Messages with Pluralization Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Use the localizer to lookup messages, supporting named variables and pluralization rules. Provide a default message and template data. ```go localizer.Localize(&i18n.LocalizeConfig{ DefaultMessage: &i18n.Message{ ID: "PersonCats", One: "{{.Name}} has {{.Count}} cat.", Other: "{{.Name}} has {{.Count}} cats.", }, TemplateData: map[string]interface{}{ "Name": "Nick", "Count": 2, }, PluralCount: 2, }) // Nick has 2 cats. ``` -------------------------------- ### Define Simple and Pluralized Messages with Custom Delimiters in Go Source: https://context7.com/nicksnyder/go-i18n/llms.txt Defines `i18n.Message` structs for simple strings, pluralized messages with named template variables, and messages with custom template delimiters. Shows how to use `i18n.NewLocalizer` and `localizer.MustLocalize` with a `DefaultMessage`. ```go // Simple message (Other covers all plural forms for English) helloMsg := &i18n.Message{ ID: "HelloWorld", Other: "Hello, World!", } // Pluralized message with named template variables emailMsg := &i18n.Message{ ID: "UnreadEmails", Description: "Number of unread emails for a named person", One: "{{.Name}} has {{.Count}} unread email.", Other: "{{.Name}} has {{.Count}} unread emails.", } // Message with custom template delimiters (avoids conflicts with other template engines) customDelimMsg := &i18n.Message{ ID: "Greeting", Other: "Hello <<.Name>>!", LeftDelim: "<<", RightDelim: ">>", } localizer := i18n.NewLocalizer(bundle, "en") fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{ DefaultMessage: customDelimMsg, TemplateData: map[string]string{"Name": "World"}, })) // Hello World! ``` -------------------------------- ### Merge Translation Files with goi18n CLI Source: https://context7.com/nicksnyder/go-i18n/llms.txt Command to generate and update translation files. It reads existing message files and produces two files per non-source language: a complete translation file (`.active.`) and a stub file for untranslated messages (`.translate.`). Supports custom output directories and formats. ```bash # Step 1: After running extract, create an empty stub for Spanish touch translate.es.toml # Step 2: Populate translate.es.toml with messages needing translation goi18n merge active.en.toml translate.es.toml # translate.es.toml now contains: # [PersonCats] # hash = "sha1-..." # one = "{{.Name}} has {{.Count}} cat." # other = "{{.Name}} has {{.Count}} cats." # Step 3: Translate the messages manually, then rename mv translate.es.toml active.es.toml # Edit active.es.toml to have Spanish translations # Step 4: After adding new messages to Go source, re-extract and re-merge all at once goi18n extract goi18n merge active.*.toml # Step 5: After translating the new translate.*.toml files, merge them in goi18n merge active.*.toml translate.*.toml # Use -outdir and -format flags for custom setups goi18n merge -outdir ./locales -format json active.en.json translate.de.json ``` -------------------------------- ### Register Message File Format Unmarshal Functions Source: https://context7.com/nicksnyder/go-i18n/llms.txt Registers unmarshal functions for TOML, YAML, and JSON formats to enable the bundle to parse message files of these types. JSON is supported by default, but TOML and YAML require explicit registration. ```go import ( "encoding/json" "github.com/BurntSushi/toml" yaml "go.yaml.in/yaml/v3" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) bundle.RegisterUnmarshalFunc("yaml", yaml.Unmarshal) bundle.RegisterUnmarshalFunc("json", json.Unmarshal) ``` -------------------------------- ### localizer.LocalizeMessage Source: https://context7.com/nicksnyder/go-i18n/llms.txt A convenience wrapper around Localize that accepts a *Message directly as the DefaultMessage, with no additional configuration needed. ```APIDOC ## localizer.LocalizeMessage ### Description A convenience wrapper around `Localize` that accepts a `*Message` directly as the `DefaultMessage`, with no additional configuration needed. ### Method `localizer.LocalizeMessage(message *Message, templateData map[string]interface{}, pluralCount int) (string, error)` ### Parameters #### Path Parameters - **message** (*Message) - Required - The `*Message` struct to localize. - **templateData** (map[string]interface{}) - Optional - Data to be used for rendering the message template. - **pluralCount** (int) - Optional - The count to use for pluralization. ### Request Example ```go import ( "fmt" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) // Assuming bundle is an initialized i18n.Bundle bundle := i18n.NewBundle(language.English) catMsg := &i18n.Message{ ID: "Cats", One: "I have {{.PluralCount}} cat.", Other: "I have {{.PluralCount}} cats.", } for _, count := range []int{0, 1, 5} { localizer := i18n.NewLocalizer(bundle, "en") // Note: PluralCount must be set in LocalizeConfig; LocalizeMessage uses "Other" for all counts msg, _ := localizer.Localize(&i18n.LocalizeConfig{ DefaultMessage: catMsg, PluralCount: count, }) fmt.Println(msg) } // I have 0 cats. // I have 1 cat. // I have 5 cats. ``` ``` -------------------------------- ### bundle.LanguageTags Source: https://context7.com/nicksnyder/go-i18n/llms.txt Returns all loaded language tags from the bundle, useful for UI elements or validation. ```APIDOC ## `bundle.LanguageTags` — List all loaded languages Returns all `language.Tag` values for translations loaded into the bundle. Useful for rendering a language-selection UI or validating that required locales are present. ```go bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) bundle.MustLoadMessageFile("active.es.toml") bundle.MustLoadMessageFile("active.fr.toml") for _, tag := range bundle.LanguageTags() { fmt.Println(tag) } // en // es // fr ``` ``` -------------------------------- ### bundle.LoadMessageFile / bundle.MustLoadMessageFile Source: https://context7.com/nicksnyder/go-i18n/llms.txt Loads translation messages from a file on the operating system's filesystem. The function infers the language tag and message format from the filename. `MustLoadMessageFile` is a convenience function that panics if loading fails, suitable for initialization. ```APIDOC ## bundle.LoadMessageFile / bundle.MustLoadMessageFile — Load translations from a file path Reads a translation file from the OS filesystem, infers the language tag and format from the filename, then parses and registers all messages. `MustLoadMessageFile` panics on error, suitable for initialization code where missing files are fatal. ```go bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) // Returns an error — handle gracefully mf, err := bundle.LoadMessageFile("active.es.toml") if err != nil { log.Fatalf("failed to load: %v", err) } fmt.Printf("Loaded %d messages for %s\n", len(mf.Messages), mf.Tag) // Panics on failure — use during app startup bundle.MustLoadMessageFile("active.fr.toml") ``` ``` -------------------------------- ### localizer.LocalizeWithTag Source: https://context7.com/nicksnyder/go-i18n/llms.txt Same as Localize but also returns the language.Tag that was actually used to render the message. Useful for logging which language was served or for debugging fallback behavior. ```APIDOC ## localizer.LocalizeWithTag ### Description Same as `Localize` but also returns the `language.Tag` that was actually used to render the message. Useful for logging which language was served or for debugging fallback behavior. ### Method `localizer.LocalizeWithTag(config *LocalizeConfig) (string, language.Tag, error)` ### Parameters #### Path Parameters - **config** (*LocalizeConfig) - Required - Configuration for the localization request. - **MessageID** (string) - Optional - The ID of the message to look up. - **DefaultMessage** (*Message) - Optional - A default message to use if the message ID is not found in the bundle. - **TemplateData** (map[string]interface{}) - Optional - Data to be used for rendering the message template. - **PluralCount** (int) - Optional - The count to use for pluralization. ### Request Example ```go import ( "fmt" "log" "golang.org/x/text/language" "github.com/nicksnyder/go-i18n/v2/i18n" ) // Assuming localizer is an initialized *i18n.Localizer msg, tag, err := localizer.LocalizeWithTag(&i18n.LocalizeConfig{ DefaultMessage: &i18n.Message{ ID: "Farewell", Other: "Goodbye!", }, }) if err != nil { // May be a MessageNotFoundErr with a best-effort msg still set log.Printf("warn: %v (served %q in %s)", err, msg, tag) } else { fmt.Printf("Served %q in language %s\n", msg, tag) // e.g. language: en } ``` ``` -------------------------------- ### i18n.NewBundle Source: https://context7.com/nicksnyder/go-i18n/llms.txt Initializes a new translation bundle with a specified default language. This bundle is intended to be created once at application startup and shared globally. It stores all loaded message templates and plural rules for registered languages. ```APIDOC ## i18n.NewBundle — Create an application-wide translation bundle `NewBundle` initializes a `Bundle` with a default language. The bundle is meant to be created once at application startup and shared globally. It holds all loaded message templates and the plural rules for every registered language. ```go import ( "github.com/BurntSushi/toml" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) // Load translations from disk if _, err := bundle.LoadMessageFile("active.es.toml"); err != nil { log.Fatalf("failed to load translations: %v", err) } // List all loaded language tags for _, tag := range bundle.LanguageTags() { fmt.Println(tag) // e.g. "en", "es" } ``` ``` -------------------------------- ### Extract Messages with goi18n CLI Source: https://context7.com/nicksnyder/go-i18n/llms.txt Command to extract `i18n.Message` and `i18n.LocalizeConfig` struct literals from Go source files into translation files. Supports specifying source language, output directory, and format (TOML, JSON, YAML). ```bash # Extract all messages from current directory into active.en.toml goi18n extract # Extract from specific directories with YAML output goi18n extract -sourceLanguage en -outdir ./locales -format yaml ./cmd ./internal # Resulting active.en.toml (example): # [PersonCats] # description = "The number of cats a person has" # one = "{{.Name}} has {{.Count}} cat." # other = "{{.Name}} has {{.Count}} cats." ``` -------------------------------- ### Look Up Message and Panic on Error with localizer.MustLocalize Source: https://context7.com/nicksnyder/go-i18n/llms.txt Identical to `Localize` but panics instead of returning an error. Convenient when the caller guarantees the message exists and error handling is unnecessary. ```go bundle := i18n.NewBundle(language.English) localizer := i18n.NewLocalizer(bundle, "en") // Using DefaultMessage so no file is needed greeting := localizer.MustLocalize(&i18n.LocalizeConfig{ DefaultMessage: &i18n.Message{ ID: "HelloPerson", Other: "Hello {{.Name}}!", }, TemplateData: map[string]string{"Name": "Nick"}, }) fmt.Println(greeting) // Hello Nick! ``` -------------------------------- ### Parse Translations from In-Memory Bytes Source: https://context7.com/nicksnyder/go-i18n/llms.txt Parses translation messages directly from byte slices using `ParseMessageFileBytes`. The `path` argument is used solely for inferring language and format, making it suitable for testing or dynamic loading scenarios. Includes a panic variant `MustParseMessageFileBytes` for initialization. ```go bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) tomlContent := []byte(" [HelloWorld] other = \"Hola Mundo!\" ") mf, err := bundle.ParseMessageFileBytes(tomlContent, "es.toml") if err != nil { log.Fatal(err) } fmt.Printf("Loaded %d messages for %s\n", len(mf.Messages), mf.Tag) // Output: Loaded 1 messages for es // Panic variant for use during init bundle.MustParseMessageFileBytes([]byte(`HelloWorld = "Bonjour le monde!"`), "fr.toml") ``` -------------------------------- ### localizer.Localize Source: https://context7.com/nicksnyder/go-i18n/llms.txt The primary lookup method. It accepts a LocalizeConfig which specifies the message ID, optional template data, and an optional plural count. Returns the rendered string and an error (e.g. MessageNotFoundErr). ```APIDOC ## localizer.Localize ### Description The primary lookup method. It accepts a `*LocalizeConfig` which specifies the message ID, optional template data, and an optional plural count. Returns the rendered string and an error (e.g. `*MessageNotFoundErr`). ### Method `localizer.Localize(config *LocalizeConfig) (string, error)` ### Parameters #### Path Parameters - **config** (*LocalizeConfig) - Required - Configuration for the localization request. - **MessageID** (string) - Optional - The ID of the message to look up. - **DefaultMessage** (*Message) - Optional - A default message to use if the message ID is not found in the bundle. - **TemplateData** (map[string]interface{}) - Optional - Data to be used for rendering the message template. - **PluralCount** (int) - Optional - The count to use for pluralization. ### Request Example ```go import ( "fmt" "log" "github.com/nicksnyder/go-i18n/v2/i18n" ) // Assuming localizer is an initialized *i18n.Localizer // Simple message lookup by ID (requires message to exist in bundle) msg, err := localizer.Localize(&i18n.LocalizeConfig{ MessageID: "WelcomeMessage", }) if err != nil { // *i18n.MessageNotFoundErr if missing; still returns best-effort string log.Printf("localize error: %v", err) } fmt.Println(msg) // With a default message (no bundle file required for default language) msg, err = localizer.Localize(&i18n.LocalizeConfig{ DefaultMessage: &i18n.Message{ ID: "PersonCats", One: "{{.Name}} has {{.Count}} cat.", Other: "{{.Name}} has {{.Count}} cats.", }, TemplateData: map[string]interface{}{ "Name": "Alice", "Count": 3, }, PluralCount: 3, }) // msg == "Alice has 3 cats." ``` ``` -------------------------------- ### bundle.RegisterUnmarshalFunc Source: https://context7.com/nicksnyder/go-i18n/llms.txt Registers a custom function to deserialize message files for a given file extension. This allows the bundle to parse message files in formats like TOML or YAML, in addition to the built-in JSON support. ```APIDOC ## bundle.RegisterUnmarshalFunc — Register a format deserializer Registers an unmarshal function for a specific file extension so the bundle knows how to parse message files of that format. JSON is supported out of the box; TOML and YAML require explicit registration. ```go import ( "encoding/json" "github.com/BurntSushi/toml" yaml "go.yaml.in/yaml/v3" "github.com/nicksnyder/go-i18n/v2/i18n" "golang.org/x/text/language" ) bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) bundle.RegisterUnmarshalFunc("yaml", yaml.Unmarshal) bundle.RegisterUnmarshalFunc("json", json.Unmarshal) ``` ``` -------------------------------- ### Extract Messages with goi18n Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Use the `goi18n extract` command to find `i18n.Message` struct literals in Go source files and generate a message file for translation. ```toml # active.en.toml [PersonCats] description = "The number of cats a person has" one = "{{.Name}} has {{.Count}} cat." other = "{{.Name}} has {{.Count}} cats." ``` -------------------------------- ### bundle.ParseMessageFileBytes / bundle.MustParseMessageFileBytes Source: https://context7.com/nicksnyder/go-i18n/llms.txt Parses translation messages directly from a byte slice in memory. The `path` parameter is used solely for inferring the language tag and format, not for reading from disk. This is useful for testing or dynamic loading scenarios. ```APIDOC ## bundle.ParseMessageFileBytes / bundle.MustParseMessageFileBytes — Parse translations from in-memory bytes Parses message file content already loaded into memory. The `path` argument is not read from disk; it is used only to infer the language tag and format. Useful for testing or dynamic translation loading. ```go bundle := i18n.NewBundle(language.English) bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) tomContent := []byte( "[HelloWorld]\n" "other = \"Hola Mundo!\"" ) mf, err := bundle.ParseMessageFileBytes(tomlContent, "es.toml") if err != nil { log.Fatal(err) } fmt.Printf("Loaded %d messages for %s\n", len(mf.Messages), mf.Tag) // Output: Loaded 1 messages for es // Panic variant for use during init bundle.MustParseMessageFileBytes([]byte(`HelloWorld = "Bonjour le monde!"`), "fr.toml") ``` ``` -------------------------------- ### LocalizeConfig Source: https://context7.com/nicksnyder/go-i18n/llms.txt Configures a localization call, controlling message resolution, template rendering, and pluralization. ```APIDOC ## `LocalizeConfig` — Configure a localization call `LocalizeConfig` is the parameter struct for `Localize` and `MustLocalize`. It controls message resolution, template rendering, and pluralization. ```go // All fields demonstrated msg, err := localizer.Localize(&i18n.LocalizeConfig{ // MessageID is used when the message is loaded from a file, not inline MessageID: "WelcomeBack", // DefaultMessage is used when MessageID is not found (or as the primary for default lang) DefaultMessage: &i18n.Message{ ID: "WelcomeBack", Other: "Welcome back, {{.Name}}! You have {{.Count}} notifications.", }, // TemplateData is passed to text/template execution TemplateData: map[string]interface{}{ "Name": "Alice", "Count": 7, }, // PluralCount selects the plural form (One/Other/etc.) and auto-sets .PluralCount in template PluralCount: 7, // Funcs adds custom template functions Funcs: template.FuncMap{ "upper": strings.ToUpper, }, }) if err != nil { log.Printf("localization error: %v", err) } fmt.Println(msg) // Welcome back, Alice! You have 7 notifications. ``` ``` -------------------------------- ### localizer.MustLocalize Source: https://context7.com/nicksnyder/go-i18n/llms.txt Identical to Localize but panics instead of returning an error. Convenient when the caller guarantees the message exists and error handling is unnecessary. ```APIDOC ## localizer.MustLocalize ### Description Identical to `Localize` but panics instead of returning an error. Convenient when the caller guarantees the message exists and error handling is unnecessary. ### Method `localizer.MustLocalize(config *LocalizeConfig) string` ### Parameters #### Path Parameters - **config** (*LocalizeConfig) - Required - Configuration for the localization request. - **MessageID** (string) - Optional - The ID of the message to look up. - **DefaultMessage** (*Message) - Optional - A default message to use if the message ID is not found in the bundle. - **TemplateData** (map[string]interface{}) - Optional - Data to be used for rendering the message template. - **PluralCount** (int) - Optional - The count to use for pluralization. ### Request Example ```go import ( "fmt" "golang.org/x/text/language" "github.com/nicksnyder/go-i18n/v2/i18n" ) // Assuming bundle is an initialized i18n.Bundle bundle := i18n.NewBundle(language.English) localizer := i18n.NewLocalizer(bundle, "en") // Using DefaultMessage so no file is needed greeting := localizer.MustLocalize(&i18n.LocalizeConfig{ DefaultMessage: &i18n.Message{ ID: "HelloPerson", Other: "Hello {{.Name}}!", }, TemplateData: map[string]string{"Name": "Nick"}, }) fmt.Println(greeting) // Hello Nick! ``` ``` -------------------------------- ### bundle.AddMessages Source: https://context7.com/nicksnyder/go-i18n/llms.txt Adds Message structs directly to the bundle without a file. This is useful when translations are sourced from a database, remote API, or any non-file storage. ```APIDOC ## bundle.AddMessages ### Description Adds `*Message` structs directly to the bundle without a file. This is useful when translations are sourced from a database, remote API, or any non-file storage. ### Method `bundle.AddMessages(lang language.Tag, msgs ...*Message)` ### Parameters #### Path Parameters - **lang** (language.Tag) - Required - The language tag for the messages being added. - **msgs** (*Message) - Required - A variadic list of `*Message` structs to add to the bundle. ### Request Example ```go import ( "log" "golang.org/x/text/language" "github.com/nicksnyder/go-i18n/v2/i18n" ) // Assuming bundle is an initialized i18n.Bundle bundle := i18n.NewBundle(language.English) err := bundle.AddMessages(language.Spanish, &i18n.Message{ ID: "Greeting", Other: "¡Hola, {{.Name}}!", }, &i18n.Message{ ID: "ItemCount", One: "Tienes {{.PluralCount}} artículo.", Other: "Tienes {{.PluralCount}} artículos.", }, ) if err != nil { log.Fatalf("AddMessages failed: %v", err) } ``` ``` -------------------------------- ### Update Translations with goi18n Merge Source: https://github.com/nicksnyder/go-i18n/blob/main/README.md Use `goi18n merge` to update active message files with newly translated messages from temporary translate files, and vice-versa. ```bash goi18n merge active.en.toml translate.es.toml ``` ```bash goi18n merge active.*.toml ``` ```bash goi18n merge active.*.toml translate.*.toml ``` -------------------------------- ### goi18n extract Source: https://context7.com/nicksnyder/go-i18n/llms.txt Extracts translatable messages from Go source files into a specified translation file format. ```APIDOC ## Command goi18n ### `goi18n extract` — Extract messages from Go source into a translation file Walks Go source files in the specified paths (or current directory) and extracts all `i18n.Message` and `i18n.LocalizeConfig` struct literals into an `active..` file. Skips `_test.go` files. Supports TOML, JSON, and YAML output. ```bash # Install the tool go install github.com/nicksnyder/go-i18n/v2/goi18n@latest # Extract all messages from current directory into active.en.toml goi18n extract # Extract from specific directories with YAML output goi18n extract -sourceLanguage en -outdir ./locales -format yaml ./cmd ./internal # Resulting active.en.toml (example): # [PersonCats] # description = "The number of cats a person has" # one = "{{.Name}} has {{.Count}} cat." # other = "{{.Name}} has {{.Count}} cats." ``` ``` -------------------------------- ### goi18n merge Source: https://context7.com/nicksnyder/go-i18n/llms.txt Generates and updates translation files by merging existing translations with new or modified messages. ```APIDOC ### `goi18n merge` — Generate and update translation files Reads all provided message files and produces two files per non-source language: - `.active.` — complete translations ready to load at runtime - `.translate.` — messages that still need translation (empty stubs) ```bash # Step 1: After running extract, create an empty stub for Spanish touch translate.es.toml # Step 2: Populate translate.es.toml with messages needing translation goi18n merge active.en.toml translate.es.toml # translate.es.toml now contains: # [PersonCats] # hash = "sha1-..." # one = "{{.Name}} has {{.Count}} cat." # other = "{{.Name}} has {{.Count}} cats." # Step 3: Translate the messages manually, then rename mv translate.es.toml active.es.toml # Edit active.es.toml to have Spanish translations # Step 4: After adding new messages to Go source, re-extract and re-merge all at once goi18n extract goi18n merge active.*.toml # Step 5: After translating the new translate.*.toml files, merge them in goi18n merge active.*.toml translate.*.toml # Use -outdir and -format flags for custom setups goi18n merge -outdir ./locales -format json active.en.json translate.de.json ``` ``` -------------------------------- ### i18n.Message Source: https://context7.com/nicksnyder/go-i18n/llms.txt Defines a translatable message with support for CLDR plural forms, custom delimiters, and translator context. ```APIDOC ## `i18n.Message` — Define a translatable message `Message` is the core data structure representing a single translatable string. It supports all six CLDR plural forms (`Zero`, `One`, `Two`, `Few`, `Many`, `Other`), custom template delimiters, and an optional description for translator context. ```go // Simple message (Other covers all plural forms for English) helloMsg := &i18n.Message{ ID: "HelloWorld", Other: "Hello, World!", } // Pluralized message with named template variables emailMsg := &i18n.Message{ ID: "UnreadEmails", Description: "Number of unread emails for a named person", One: "{{.Name}} has {{.Count}} unread email.", Other: "{{.Name}} has {{.Count}} unread emails.", } // Message with custom template delimiters (avoids conflicts with other template engines) customDelimMsg := &i18n.Message{ ID: "Greeting", Other: "Hello <<.Name>>!", LeftDelim: "<<", RightDelim: ">>", } localizer := i18n.NewLocalizer(bundle, "en") fmt.Println(localizer.MustLocalize(&i18n.LocalizeConfig{ DefaultMessage: customDelimMsg, TemplateData: map[string]string{"Name": "World"}, })) // Hello World! ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.