i18n

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2025 License: MIT Imports: 10 Imported by: 0

README

Nyx i18n

i18n - Go Internationalization Library

Go Version License Go Report Card GoDoc

A simple, efficient Go internationalization (i18n) library with 0-based indexing and file-based dictionaries.

Quick Start

1. Write Code with i18n Functions
import "github.com/nyxstack/i18n"

func myFunction() {
    // Use simple single-character i18n functions
    greeting := i18n.F("Hello %s", "World")   // Format with placeholders
    title := i18n.S("Dashboard")              // Static text
    bye := i18n.T("goodbye")                  // Direct key lookup
    
    // Get translations for different locales
    fmt.Println(greeting("en"))  // "Hello World"
    fmt.Println(greeting("fr"))  // "Bonjour World"
    fmt.Println(title("fr"))     // "Tableau de bord"
}
2. Extract Translations

Option A: Programmatically

// Generate translation file from your Go source code
err := i18n.GenerateTranslations("en", "./", "")
// Output: ✅ Extracted 2 i18n entries → locales/default.en.json

Option B: CLI

go run github.com/nyxstack/i18n/cmd/extract-i18n@latest <source_dir> <locale>
3. Create Translation Files

Generation creates locales/default.en.json:

{
  "meta": {
    "lang": "en",
    "name": "default"
  },
  "translations": {
    "hello-0": "Hello %s",
    "dashboard": "Dashboard"
  }
}

Create locales/default.fr.json for French:

{
  "meta": {
    "lang": "fr", 
    "name": "default"
  },
  "translations": {
    "hello-0": "Bonjour %s",
    "dashboard": "Tableau de bord"
  }
}
4. Load and Use
func main() {
    // Load dictionaries
    i18n.Load()              // Loads locales/default.en.json
    i18n.LoadLanguage("fr")  // Loads locales/default.fr.json
    i18n.SetDefaultLanguage("en")
    
    // Use your translations
    greeting := i18n.F("Hello %s", "World")
    fmt.Println(greeting("fr"))  // "Bonjour World"
}

Translation Functions

All functions return func(locale string) string for easy use:

Function Purpose Example
F(format, args...) Format string with placeholders F("Hello %s", "John")
S(text) Static text S("Dashboard")
T(key, args...) Direct key with placeholders T("welcome", "John")
P(key, count) Pluralization P("item_count", 5)

Dictionary Management

Dictionaries are JSON files that contain your translations. Each file represents one language:

{
  "meta": {
    "lang": "en",           // Required: language code
    "name": "default"       // Required: dictionary name
  },
  "translations": {
    "hello-0": "Hello {0}!",           // 0-based placeholders
    "welcome": "Welcome",              // Static text
    "item-count": "{count, plural, one {# item} other {# items}}"  // Plurals
  }
}

Load and manage dictionaries:

// Load dictionaries
i18n.Load()                    // Loads locales/default.en.json
i18n.LoadLanguage("fr")        // Loads locales/default.fr.json
i18n.LoadFrom("custom.json")   // Load custom path
i18n.SetDefaultLanguage("en")  // Set fallback language

// Create dictionaries programmatically
dict := i18n.NewDictionary("es")
dict.Add("hello-0", "Hola {0}!")
dict.AddAll(map[string]string{
    "welcome": "Bienvenido",
    "goodbye": "Adiós",
})
i18n.Register(dict)  // Make it available

License

MIT

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes
  4. Add tests for new functionality
  5. Ensure all tests pass (go test ./...)
  6. Commit your changes (git commit -m 'Add amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

Requirements:

  • All new code must have tests
  • Tests must pass
  • Follow existing code style
  • Update documentation if needed

Documentation

Overview

Package i18n provides a comprehensive internationalization system with: - Consistent 0-based indexing for placeholders - File-based translation dictionaries - Advanced pluralization support for multiple languages - Thread-safe operations - Automatic fallback to default languages - Code generation for extracting translation keys

Basic usage:

// Load translations
i18n.Load()
i18n.LoadLanguage("fr")

// Use translations
greeting := i18n.F("Hello %s", "World")
fmt.Println(greeting("en")) // "Hello World"
fmt.Println(greeting("fr")) // "Bonjour World"

title := i18n.S("Dashboard")
fmt.Println(title("fr")) // "Tableau de bord"

count := i18n.P("item-count", 5)
fmt.Println(count("en")) // "5 items"

Package i18n provides internationalization and localization functionality.

Translation API Functions: - T(key, args...) - Translate by key with placeholder substitution - F(format, args...) - Translate by format string (auto-generates key from format) - S(text) - Translate static text (auto-generates key from text) - P(key, count) - Pluralization support - R(locale, format) - Direct translation (no function wrapping)

Example usage:

greeting := i18n.T("hello_world")
msg := i18n.F("Welcome %s!", "John")
title := i18n.S("Dashboard")

Index

Constants

View Source
const (
	DefaultLang       = "en"
	DefaultDictionary = "default"
	DefaultFolder     = "locales"
	DefaultFilePath   = "locales/default.en.json"
)

Variables

This section is empty.

Functions

func DefaultLanguage

func DefaultLanguage() string

DefaultLanguage returns the current fallback language

func Generate

func Generate(locale, root string) error

Generate is a convenience function that generates translations to the default location

func GenerateTranslations

func GenerateTranslations(locale, root, outputPath string) error

GenerateTranslations scans a Go codebase for i18n function calls (F, S, T, P) and generates translation keys + source strings into a dictionary file in the locales/ folder.

func Load

func Load() error

Load auto-loads the default dictionary from locales/default.en.json

func LoadFrom

func LoadFrom(path string) error

LoadFrom loads and registers a dictionary from a specific path

func LoadLanguage

func LoadLanguage(lang string) error

LoadLanguage loads a dictionary for a specific language from locales/default.{lang}.json

func R

func R(locale, text string) string

R performs direct translation without function wrapping. Use this when you want immediate translation without creating a TranslatedFunc.

Example:

text := i18n.R("en", "Dashboard")
fmt.Println(text) // "Dashboard"

func Register

func Register(dict *Dictionary)

Register adds a dictionary to the global registry

func SetDefaultLanguage

func SetDefaultLanguage(lang string)

SetDefaultLanguage sets the fallback language code

Types

type Dictionary

type Dictionary struct {
	Lang         string
	Translations map[string]string
	// contains filtered or unexported fields
}

Dictionary represents one language's translations

func GetDictionary

func GetDictionary(lang string) *Dictionary

GetDictionary returns a dictionary by language code

func LoadDictionaryFile

func LoadDictionaryFile(path string) (*Dictionary, error)

LoadDictionaryFile loads a single dictionary file

func NewDictionary

func NewDictionary(lang string) *Dictionary

NewDictionary creates an empty dictionary for a language

func (*Dictionary) Add

func (d *Dictionary) Add(key, value string)

Add inserts or updates a translation

func (*Dictionary) AddAll

func (d *Dictionary) AddAll(translations map[string]string)

AddAll merges translations from a map

func (*Dictionary) Count

func (d *Dictionary) Count() int

Count returns the number of translations

func (*Dictionary) Get

func (d *Dictionary) Get(key string) string

Get retrieves a translation with fallback to default language

func (*Dictionary) Has

func (d *Dictionary) Has(key string) bool

Has checks if a translation key exists

func (*Dictionary) Keys

func (d *Dictionary) Keys() []string

Keys returns all translation keys

type TranslatedFunc

type TranslatedFunc func(locale string) string

TranslatedFunc returns a localized string when called with a locale. This allows you to prepare a translation function and call it later with different locales.

func F

func F(format string, args ...any) TranslatedFunc

F translates by format string with auto-generated key. This automatically generates a translation key from the format string and normalizes placeholders. Use this when you want to use the English text as the source and auto-generate keys.

Example:

fn := i18n.F("Hello %s, you have %d messages", "John", 5)
fmt.Println(fn("en")) // "Hello John, you have 5 messages"
fmt.Println(fn("fr")) // "Bonjour John, vous avez 5 messages"

Auto-generated key: "hello-1-you-have-2-messages" Dictionary should contain:

"hello-1-you-have-2-messages": "Bonjour {0}, vous avez {1} messages"

func P

func P(key string, count int) TranslatedFunc

P handles pluralization for a given key and count. Supports ICU-style plural forms: zero, one, two, few, many, other.

Example:

fn := i18n.P("item_count", 5)
fmt.Println(fn("en")) // "5 items"

Dictionary should contain:

"item_count": "{count, plural, zero {no items} one {# item} other {# items}}"

func S

func S(text string) TranslatedFunc

S translates static text with auto-generated key. Use this for simple static strings without placeholders.

Example:

fn := i18n.S("Dashboard")
fmt.Println(fn("en")) // "Dashboard"
fmt.Println(fn("fr")) // "Tableau de bord"

Auto-generated key: "dashboard" Dictionary should contain:

"dashboard": "Tableau de bord"

func T

func T(key string, args ...any) TranslatedFunc

T translates by exact key with placeholder substitution. Use this when you have predefined translation keys in your dictionary files. Placeholders are numbered: {0}, {1}, {2}, etc.

Example:

fn := i18n.T("welcome_user", "John")
fmt.Println(fn("en")) // "Welcome John!"
fmt.Println(fn("fr")) // "Bienvenue John!"

Dictionary should contain:

"welcome_user": "Welcome {0}!"

type TranslationFile

type TranslationFile struct {
	Meta struct {
		Lang      string `json:"lang"`
		Name      string `json:"name"`
		Version   string `json:"version,omitempty"`
		Author    string `json:"author,omitempty"`
		Updated   string `json:"updated,omitempty"`
		Direction string `json:"direction,omitempty"`
	} `json:"meta"`
	Translations map[string]string `json:"translations"`
}

TranslationFile represents a single dictionary file

Directories

Path Synopsis
cmd
extract-i18n command
CLI tool for extracting i18n translation keys from Go source code
CLI tool for extracting i18n translation keys from Go source code

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL