i18n

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 9 Imported by: 1

README

i18n

Unified internationalization module for Go: locale detection, translation lookup with fallback, locale-specific formatting, and pluggable machine-translation backends.

Structure

i18n/
├── i18n.go              # Manager, Locale, Config, translation storage
├── context.go           # context.Context locale helpers
├── locale.go            # Accept-Language parsing, locale resolution
├── formatter.go         # number / currency / date / relative-time formatting
├── translator.go        # Translator interface (implementations in sub-modules)
├── translations/        # bundled JSON translation files
│   ├── messages.en.json
│   ├── messages.zh-CN.json
│   └── messages.zh-TW.json
├── gin/                 # optional Gin middleware (separate module)
│   ├── go.mod
│   └── middleware.go
└── mymemory/            # optional MyMemory MT backend (separate module)
    ├── go.mod
    └── translator.go

Design: Core + Optional Sub-Modules

The core i18n package has zero external dependencies — it only needs the Go standard library. Optional integrations live in separate Go modules:

# Core only (no HTTP framework, no external MT API)
go get github.com/LingByte/ling-base/i18n

# With Gin middleware
go get github.com/LingByte/ling-base/i18n/gin

# With MyMemory machine translation
go get github.com/LingByte/ling-base/i18n/mymemory

Quick Start

Basic Manager
import "github.com/LingByte/ling-base/i18n"

manager := i18n.NewManager(&i18n.Config{
    DefaultLocale:    i18n.LocaleEn,
    SupportedLocales: []i18n.Locale{i18n.LocaleEn, i18n.LocaleZhCN, i18n.LocaleZhTW},
    FallbackLocale:   i18n.LocaleEn,
    TranslationsPath: "./translations", // load JSON files from directory
})

// Translate
msg := manager.T(i18n.LocaleZhCN, "common.success")
// → "成功"

// With printf-style args
msg = manager.T(i18n.LocaleEn, "hello", "World")
// → "Hello, World!"
Loading Translation Files

Translation files are JSON key → value maps. The locale is extracted from the filename suffix:

translations/
├── messages.en.json      → locale "en"
├── messages.zh-CN.json   → locale "zh-CN"
└── messages.zh-TW.json   → locale "zh-TW"
// Load all files from a directory
manager.LoadTranslations("./translations")

// Load a single file
manager.LoadTranslationFile(i18n.LocaleJaJP, "./messages.ja-JP.json")

// Set a translation programmatically
manager.SetTranslation(i18n.LocaleEn, "custom.key", "Custom Value")
Locale Detection
// From Accept-Language header
locale := manager.ParseAcceptLanguage("zh-CN,zh;q=0.9,en;q=0.8")
// → i18n.LocaleZhCN

// From a raw locale string
locale := manager.ResolveLocale("zh_CN")
// → i18n.LocaleZhCN (underscore normalised)

// From a context.Context
ctx := i18n.WithLocale(context.Background(), i18n.LocaleZhCN)
locale := i18n.GetLocaleFromContext(ctx)
Formatting
f := i18n.NewFormatter(i18n.LocaleEn)

f.FormatNumber(1234.56, 2)           // "1,234.56"
f.FormatCurrency(1234.56, "USD")     // "$1,234.56"
f.FormatDate(time.Now(), "YYYY-MM-DD") // "2024-01-15"
f.FormatRelativeTime(pastTime)       // "2 hours ago"

fCN := i18n.NewFormatter(i18n.LocaleZhCN)
fCN.FormatCurrency(1234.56, "CNY")   // "¥1,234.56"
fCN.FormatRelativeTime(pastTime)     // "2 小时前"
Gin Middleware
import (
    "github.com/LingByte/ling-base/i18n"
    i18ngin "github.com/LingByte/ling-base/i18n/gin"
    "github.com/gin-gonic/gin"
)

manager := i18n.NewManager(&i18n.Config{
    SupportedLocales: []i18n.Locale{i18n.LocaleEn, i18n.LocaleZhCN},
    DefaultLocale:    i18n.LocaleEn,
    TranslationsPath: "./translations",
})

r := gin.New()
r.Use(i18ngin.Middleware(manager))

r.GET("/hello", func(c *gin.Context) {
    // Locale auto-detected from ?locale=, Accept-Language header, or cookie
    i18ngin.ResponseJSON(c, 200, "common.success", gin.H{"locale": i18ngin.GetLocale(c)})
})

Detection order: ?locale= query param → Accept-Language header → locale cookie → default.

Machine Translation (MyMemory)
import (
    "github.com/LingByte/ling-base/i18n"
    "github.com/LingByte/ling-base/i18n/mymemory"
)

translator := mymemory.New("your-email@example.com") // email optional
manager := i18n.NewManager(&i18n.Config{
    Translator: translator,
})

result, err := manager.Translate("Hello", "en", "zh-CN")
// → "你好"

API Reference

Manager
Method Description
NewManager(*Config) *Manager Create a manager
T(locale, key, args...) string Translate with printf-style args
GetTranslation(locale, key) string Lookup with fallback
SetTranslation(locale, key, value) Set a single translation
LoadTranslations(path) error Load JSON files from directory
LoadTranslationFile(locale, path) error Load a single JSON file
Translate(text, from, to) (string, error) Machine translation
ParseAcceptLanguage(header) Locale Parse Accept-Language header
ResolveLocale(raw) Locale Normalise a locale string
GetDefaultLocale() Locale Get default locale
GetSupportedLocales() []Locale Get supported locales
IsSupportedLocale(locale) bool Check if supported
Formatter
Method Description
NewFormatter(locale) *Formatter Create a formatter
FormatNumber(n, decimals) string Locale-specific number
FormatCurrency(amount, currency) string With currency symbol
FormatDate(time, format) string Token-based date format
FormatRelativeTime(time) string "2 hours ago" style
Context Helpers
Function Description
WithLocale(ctx, locale) context.Context Attach locale to context
GetLocaleFromContext(ctx) Locale Extract locale from context

Supported Locales

Built-in constants: en, en-US, en-GB, zh-CN, zh-TW, ja-JP, ko-KR, fr-FR, de-DE, es-ES. Custom locales can be added via Config.SupportedLocales.

Testing

# Core (no external deps)
cd i18n && go test -cover

# Gin middleware
cd i18n/gin && go test -cover

# MyMemory translator
cd i18n/mymemory && go test -cover

Coverage:

  • i18n (core): ~84%
  • i18n/gin: ~94%
  • i18n/mymemory: ~86%

Documentation

Overview

Package i18n provides a unified internationalization module supporting locale detection, translation lookup with fallback, locale-specific formatting, and pluggable machine-translation backends.

The core package has zero external dependencies. Optional integrations live in sub-modules:

i18n/gin       — Gin middleware and helpers
i18n/mymemory  — MyMemory API translator

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetLocale

func SetLocale(ctx context.Context, locale Locale) context.Context

SetLocale is an alias for WithLocale.

func WithLocale

func WithLocale(ctx context.Context, locale Locale) context.Context

WithLocale returns a new context with the locale attached.

Types

type Config

type Config struct {
	DefaultLocale    Locale   // fallback when no locale is detected; defaults to "en"
	SupportedLocales []Locale // locales this manager recognises
	FallbackLocale   Locale   // secondary fallback for missing keys; defaults to DefaultLocale
	// TranslationsPath is a directory of JSON translation files.
	// Filenames must follow the pattern: <prefix>.<locale>.json
	// e.g. messages.en.json, messages.zh-CN.json
	TranslationsPath string
	// Translator is an optional external MT backend.
	Translator Translator
}

Config holds i18n Manager configuration.

type CurrencyFormat

type CurrencyFormat struct {
	Symbol         string
	SymbolPosition string // "before" or "after"
}

CurrencyFormat holds locale-specific currency formatting rules.

type Formatter

type Formatter struct {
	// contains filtered or unexported fields
}

Formatter handles locale-specific formatting of numbers, currency, dates, and relative time.

func NewFormatter

func NewFormatter(locale Locale) *Formatter

NewFormatter creates a formatter for the given locale.

func (*Formatter) FormatCurrency

func (f *Formatter) FormatCurrency(amount float64, currency string) string

FormatCurrency formats a monetary amount with the locale's currency symbol.

func (*Formatter) FormatDate

func (f *Formatter) FormatDate(date time.Time, format string) string

FormatDate formats a date using a token-based format string. Supported tokens: YYYY, MM, DD, HH, mm, ss. If format is empty, the locale's default date format is used.

func (*Formatter) FormatNumber

func (f *Formatter) FormatNumber(number float64, decimals int) string

FormatNumber formats a number with the given decimal places and locale-specific separators.

func (*Formatter) FormatRelativeTime

func (f *Formatter) FormatRelativeTime(t time.Time) string

FormatRelativeTime formats a time as a relative phrase (e.g. "2 hours ago").

type Locale

type Locale string

Locale represents a BCP 47 locale identifier (e.g. "en", "zh-CN", "ja-JP").

const (
	LocaleEn   Locale = "en"
	LocaleEnUS Locale = "en-US"
	LocaleEnGB Locale = "en-GB"
	LocaleZhCN Locale = "zh-CN"
	LocaleZhTW Locale = "zh-TW"
	LocaleJaJP Locale = "ja-JP"
	LocaleKoKR Locale = "ko-KR"
	LocaleFrFR Locale = "fr-FR"
	LocaleDeDE Locale = "de-DE"
	LocaleEsES Locale = "es-ES"
)

Common locale constants.

const DefaultLocale Locale = LocaleEn

DefaultLocale is used when no locale can be determined.

func GetLocaleFromContext

func GetLocaleFromContext(ctx context.Context) Locale

GetLocaleFromContext extracts the locale from a context, returning the default locale if none is set.

type Manager

type Manager struct {
	// contains filtered or unexported fields
}

Manager handles internationalization: translation storage, lookup, locale detection, and formatting.

func NewManager

func NewManager(config *Config) *Manager

NewManager creates a new i18n manager from the given config. If config is nil, sensible defaults are applied.

func (*Manager) DetectLocale

func (m *Manager) DetectLocale(lang string) Locale

DetectLocale detects a locale from a language string (e.g. "en-US", "zh-CN").

func (*Manager) GetDefaultLocale

func (m *Manager) GetDefaultLocale() Locale

GetDefaultLocale returns the manager's default locale.

func (*Manager) GetSupportedLocales

func (m *Manager) GetSupportedLocales() []Locale

GetSupportedLocales returns the list of supported locales.

func (*Manager) GetTranslation

func (m *Manager) GetTranslation(locale Locale, key string) string

GetTranslation looks up a key in the requested locale, falling back to the fallback locale, then returning the key itself if not found.

func (*Manager) GetTranslations

func (m *Manager) GetTranslations(locale Locale) map[string]string

GetTranslations returns a copy of all translations for a locale.

func (*Manager) IsSupportedLocale

func (m *Manager) IsSupportedLocale(locale Locale) bool

IsSupportedLocale reports whether the locale is in the supported list.

func (*Manager) LoadTranslationFile

func (m *Manager) LoadTranslationFile(locale Locale, filePath string) error

LoadTranslationFile loads a single JSON translation file for a locale.

func (*Manager) LoadTranslations

func (m *Manager) LoadTranslations(path string) error

LoadTranslations walks path and loads all *.json translation files. The locale is extracted from the filename suffix (e.g. "messages.zh-CN.json" → "zh-CN").

func (*Manager) ParseAcceptLanguage

func (m *Manager) ParseAcceptLanguage(header string) Locale

ParseAcceptLanguage parses an Accept-Language header value and returns the first supported locale found, or the default locale if none match.

Example header: "en-US,en;q=0.9,zh-CN;q=0.8"

func (*Manager) ResolveLocale

func (m *Manager) ResolveLocale(raw string) Locale

ResolveLocale maps a raw locale string to one of the supported locales. If the raw string doesn't match, the manager's default locale is returned.

func (*Manager) SetTranslation

func (m *Manager) SetTranslation(locale Locale, key, value string)

SetTranslation sets a single key-value pair for a locale.

func (*Manager) T

func (m *Manager) T(locale Locale, key string, args ...interface{}) string

T translates a key with optional printf-style arguments.

func (*Manager) Translate

func (m *Manager) Translate(text, from, to string) (string, error)

Translate uses the external translator backend (if configured).

type NumberFormat

type NumberFormat struct {
	DecimalSeparator  string
	ThousandSeparator string
}

NumberFormat holds locale-specific number formatting rules.

type TimeUnits

type TimeUnits struct {
	JustNow string
	Seconds string
	Minutes string
	Hours   string
	Days    string
	Months  string
	Years   string
}

TimeUnits holds translated relative-time unit labels.

type Translator

type Translator interface {
	Translate(text, from, to string) (string, error)
}

Translator is the interface for external machine-translation services. Implementations live in sub-modules (e.g. i18n/mymemory).

Directories

Path Synopsis
gin module
mymemory module

Jump to

Keyboard shortcuts

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