Convert Figma logo to code with AI

nicksnyder logogo-i18n

Translate your Go program into multiple languages.

2,974
273
2,974
11

Top Related Projects

16,709

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

4,570

TOML parser for Golang with reflection.

26,991

Go configuration with fangs

6,852

YAML support for the Go language.

Quick Overview

go-i18n is a Go package that provides internationalization (i18n) support for Go applications. It offers a simple and flexible way to manage translations, pluralization, and message formatting, making it easier to create multilingual applications.

Pros

  • Easy to use and integrate into existing Go projects
  • Supports both YAML and JSON file formats for translation messages
  • Provides pluralization support and message formatting
  • Offers a command-line tool for managing translation files

Cons

  • Limited built-in support for complex pluralization rules
  • Lacks advanced features like automatic translation or machine learning integration
  • May require additional setup for larger projects with many languages

Code Examples

  1. Basic usage:
import "github.com/nicksnyder/go-i18n/v2/i18n"

bundle := i18n.NewBundle(language.English)
localizer := i18n.NewLocalizer(bundle, "en")

message, _ := localizer.Localize(&i18n.LocalizeConfig{
    MessageID: "greeting",
    DefaultMessage: &i18n.Message{
        ID:    "greeting",
        Other: "Hello!",
    },
})
fmt.Println(message) // Output: Hello!
  1. Pluralization:
message, _ := localizer.Localize(&i18n.LocalizeConfig{
    MessageID: "items",
    DefaultMessage: &i18n.Message{
        ID:    "items",
        One:   "You have {{.Count}} item",
        Other: "You have {{.Count}} items",
    },
    TemplateData: map[string]interface{}{
        "Count": 3,
    },
    PluralCount: 3,
})
fmt.Println(message) // Output: You have 3 items
  1. Loading translations from a file:
bundle := i18n.NewBundle(language.English)
bundle.LoadMessageFile("en.json")
bundle.LoadMessageFile("es.json")

localizer := i18n.NewLocalizer(bundle, "es")

message, _ := localizer.Localize(&i18n.LocalizeConfig{
    MessageID: "welcome",
})
fmt.Println(message) // Output: Bienvenido

Getting Started

  1. Install the package:

    go get -u github.com/nicksnyder/go-i18n/v2/i18n
    
  2. Create a new bundle and localizer:

    bundle := i18n.NewBundle(language.English)
    localizer := i18n.NewLocalizer(bundle, "en")
    
  3. Define messages and localize:

    message, _ := localizer.Localize(&i18n.LocalizeConfig{
        MessageID: "hello",
        DefaultMessage: &i18n.Message{
            ID:    "hello",
            Other: "Hello, {{.Name}}!",
        },
        TemplateData: map[string]interface{}{
            "Name": "World",
        },
    })
    fmt.Println(message) // Output: Hello, World!
    

Competitor Comparisons

16,709

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving

Pros of validator

  • Focuses on data validation, offering a wide range of built-in validation rules
  • Supports custom validation functions and field-level validation
  • Provides extensive documentation and examples for various use cases

Cons of validator

  • Limited internationalization support compared to go-i18n
  • Requires more setup and configuration for complex validation scenarios
  • May have a steeper learning curve for beginners due to its extensive feature set

Code Comparison

go-i18n:

T, _ := i18n.NewTranslator("en")
message := T.Translate("greeting", map[string]interface{}{
    "Name": "John",
})

validator:

validate := validator.New()
err := validate.Struct(user)
if err != nil {
    // Handle validation errors
}

Key Differences

  • go-i18n focuses on internationalization and localization, while validator specializes in data validation
  • go-i18n provides translation functionality, whereas validator offers input validation and sanitization
  • validator has a more extensive set of built-in rules for data validation, while go-i18n excels in managing translations across multiple languages

Use Cases

  • Use go-i18n when your primary need is managing translations and localizing your application
  • Choose validator when you require robust data validation and input sanitization in your Go projects
  • Consider using both libraries together for applications that need both internationalization and data validation capabilities
4,570

TOML parser for Golang with reflection.

Pros of toml

  • Focuses specifically on TOML parsing and encoding, making it lightweight and efficient for this task
  • Provides a robust and well-tested implementation of the TOML specification
  • Offers both encoding and decoding capabilities for TOML data

Cons of toml

  • Limited to TOML format, while go-i18n supports multiple localization file formats
  • Lacks built-in internationalization features, such as pluralization and message formatting
  • Doesn't provide specific tools for managing translations across multiple languages

Code Comparison

toml:

type Config struct {
    Name string
    Age  int
}

var conf Config
_, err := toml.DecodeFile("config.toml", &conf)

go-i18n:

bundle := i18n.NewBundle(language.English)
bundle.LoadMessageFile("en.toml")
localizer := i18n.NewLocalizer(bundle, "en")
message := localizer.MustLocalize(&i18n.LocalizeConfig{MessageID: "Greeting"})

While toml focuses on parsing TOML files into Go structs, go-i18n provides a more comprehensive solution for internationalization, including message loading, localization, and formatting. toml is better suited for general TOML configuration handling, while go-i18n is specifically designed for managing translations and localized content in Go applications.

26,991

Go configuration with fangs

Pros of Viper

  • Broader functionality: Viper is a complete configuration solution, handling various config formats, environment variables, and remote config systems
  • Automatic environment variable binding and watching for config changes
  • Supports multiple configuration sources and formats (JSON, TOML, YAML, etc.)

Cons of Viper

  • More complex setup and usage compared to go-i18n's focused approach
  • Potentially overkill for projects only needing internationalization
  • Steeper learning curve due to its extensive feature set

Code Comparison

go-i18n:

bundle := i18n.NewBundle(language.English)
bundle.LoadMessageFile("en.json")
localizer := i18n.NewLocalizer(bundle, "en")
localizer.Localize(&i18n.LocalizeConfig{MessageID: "greeting"})

Viper:

viper.SetConfigName("config")
viper.AddConfigPath(".")
viper.ReadInConfig()
greeting := viper.GetString("greeting")

While go-i18n focuses specifically on internationalization, Viper provides a more comprehensive configuration management solution. go-i18n excels in handling translations and localization, whereas Viper offers a broader range of features for managing application configurations across various formats and sources. The choice between the two depends on the specific needs of your project, with go-i18n being more suitable for projects primarily focused on internationalization, and Viper being a better fit for applications requiring extensive configuration management capabilities.

6,852

YAML support for the Go language.

Pros of yaml

  • More general-purpose, suitable for various data serialization tasks
  • Supports complex data structures and custom types
  • Widely adopted in the Go community for configuration files

Cons of yaml

  • Not specifically designed for internationalization (i18n) tasks
  • Requires additional logic to handle translations and pluralization
  • May be overkill for simple localization needs

Code comparison

yaml:

type Config struct {
    Name string `yaml:"name"`
    Age  int    `yaml:"age"`
}

data := []byte(`
name: John Doe
age: 30
`)

var config Config
err := yaml.Unmarshal(data, &config)

go-i18n:

bundle := i18n.NewBundle(language.English)
bundle.LoadMessageFile("en.json")
bundle.LoadMessageFile("es.json")

localizer := i18n.NewLocalizer(bundle, "es")
message := localizer.MustLocalize(&i18n.LocalizeConfig{
    MessageID: "Greeting",
})

Summary

While yaml is a versatile library for handling YAML data in Go, go-i18n is specifically designed for internationalization tasks. yaml excels in general data serialization and configuration management, whereas go-i18n provides tailored features for managing translations and localization in Go applications. The choice between the two depends on the specific needs of your project, with go-i18n being more suitable for dedicated internationalization requirements.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

go-i18n

Build status Report card codecov Sourcegraph

go-i18n is a Go package and a command that helps you translate Go programs into multiple languages.

Package i18n

Go Reference

The i18n package provides support for looking up messages according to a set of locale preferences.

import "github.com/nicksnyder/go-i18n/v2/i18n"

Create a Bundle to use for the lifetime of your application.

bundle := i18n.NewBundle(language.English)

Load translations into your bundle during initialization.

bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
bundle.LoadMessageFile("es.toml")
// If use go:embed
//go:embed locale.*.toml
var LocaleFS embed.FS

bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
bundle.LoadMessageFileFS(LocaleFS, "locale.es.toml")

Create a Localizer to use for a set of language preferences.

func(w http.ResponseWriter, r *http.Request) {
    lang := r.FormValue("lang")
    accept := r.Header.Get("Accept-Language")
    localizer := i18n.NewLocalizer(bundle, lang, accept)
}

Use the Localizer to lookup messages.

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.

Command goi18n

Go Reference

The goi18n command manages message files used by the i18n package.

go install -v github.com/nicksnyder/go-i18n/v2/goi18n@latest
goi18n -help

Extracting messages

Use goi18n extract to extract all i18n.Message struct literals in Go source files to a message file for translation.

# active.en.toml
[PersonCats]
description = "The number of cats a person has"
one = "{{.Name}} has {{.Count}} cat."
other = "{{.Name}} has {{.Count}} cats."

Translating a new language

  1. Create an empty message file for the language that you want to add (e.g. translate.es.toml).

  2. Run goi18n merge active.en.toml translate.es.toml to populate translate.es.toml with the messages to be translated.

    # translate.es.toml
    [HelloPerson]
    hash = "sha1-5b49bfdad81fedaeefb224b0ffc2acc58b09cff5"
    other = "Hello {{.Name}}"
    
  3. After translate.es.toml has been translated, rename it to active.es.toml.

    # active.es.toml
    [HelloPerson]
    hash = "sha1-5b49bfdad81fedaeefb224b0ffc2acc58b09cff5"
    other = "Hola {{.Name}}"
    
  4. Load active.es.toml into your bundle.

    bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
    bundle.LoadMessageFile("active.es.toml")
    

Translating new messages

If you have added new messages to your program:

  1. Run goi18n extract to update active.en.toml with the new messages.
  2. Run goi18n merge active.*.toml to generate updated translate.*.toml files.
  3. Translate all the messages in the translate.*.toml files.
  4. Run goi18n merge active.*.toml translate.*.toml to merge the translated messages into the active message files.

For more information and examples:

Translations of this document

Community translations of this document may be found in the .github folder.

These translations are maintained by the community, and are not maintained by the author of this project. They are not guaranteed to be accurate or up-to-date.

License

go-i18n is available under the MIT license. See the LICENSE file for more info.