goi18n

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Apr 27, 2025 License: MIT Imports: 8 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

goi18n for DiscorgGo

Go License

goi18n is a lightweight Go package for internationalization (i18n) that simplifies the process of managing translations in your applications. It supports loading translations from JSON files, injecting variables into translation strings, fallback to a default language, and random selection from multiple translation options.


Table of Contents


Introduction

The goi18n package is designed to help developers manage translations for multi-language applications. It provides a simple and efficient way to load translations from JSON files, inject variables into translation strings, and handle fallbacks when a specific translation is not available.

Key features:

  • Supports nested keys in JSON files.
  • Allows variable injection using Go's text/template syntax.
  • Provides fallback to a default language if a translation is missing.
  • Randomly selects from multiple translation options for a single key.

Installation

To install the goi18n package, use the following command:

go get github.com/icehuntmen/goi18n

Replace github.com/icehuntmen/goi18n with the actual repository URL if it differs.


Usage

Creating an Instance

Start by creating an instance of LanguageI18N:

package main

import (
	"github.com/bwmarrin/discordgo"
	"github.com/icehuntmen/goi18n"
)

func main() {
	i18n := goi18n.NewLanguageI18N()

	// Set the default language
	i18n.SetDefault(discordgo.EnglishUS)

	// Load translation files
	err := i18n.LoadBundle(discordgo.Russian, "locales/ru.json")
	if err != nil {
		panic(err)
	}

	// Get a translation
	translation := i18n.Get(discordgo.Russian, "hello.world", goi18n.Vars{"name": "World"})
	fmt.Println(translation) // Output: Привет, World!
}

Loading Translation Files

Translation files are stored in JSON format. Here's an example of a Russian translation file (locales/ru.json):

{
  "hello": {
    "world": "Привет, {{.name}}!"
  },
  "goodbye": ["Пока!", "До свидания!"]
}

You can load this file using the LoadBundle method:

err := i18n.LoadBundle(discordgo.Russian, "locales/ru.json")
if err != nil {
    panic(err)
}

Getting Translations

To retrieve a translation for a specific locale and key, use the Get method:

translation := i18n.Get(discordgo.Russian, "hello.world", goi18n.Vars{"name": "World"})
fmt.Println(translation) // Output: Привет, World!

If the key contains variables (e.g., {{.name}}), they will be replaced with the values provided in the Vars map.


Handling Nested Keys

The package supports nested keys in JSON files. For example, if your JSON file looks like this:

{
  "hello": {
    "world": "Hello, {{.name}}!"
  }
}

You can access the nested key using dot notation:

translation := i18n.Get(discordgo.EnglishUS, "hello.world", goi18n.Vars{"name": "World"})
fmt.Println(translation) // Output: Hello, World!

Fallback to Default Language

If a translation is not available for the requested locale, the package will fall back to the default language:

defaultTranslation := i18n.GetDefault("hello.world", goi18n.Vars{"name": "World"})
fmt.Println(defaultTranslation) // Output: Hello, World!

You can set the default language using the SetDefault method:

i18n.SetDefault(discordgo.EnglishUS)

API Reference

NewLanguageI18N()

Creates a new instance of LanguageI18N.

i18n := goi18n.NewLanguageI18N()
SetDefault(locale discordgo.Locale)

Sets the default locale used as a fallback.

i18n.SetDefault(discordgo.EnglishUS)
LoadBundle(locale discordgo.Locale, path string) error

Loads a translation file for the specified locale.

err := i18n.LoadBundle(discordgo.Russian, "locales/ru.json")
Get(locale discordgo.Locale, key string, vars Vars) string

Retrieves a translation for the specified locale and key. Replaces variables in the translation string.

translation := i18n.Get(discordgo.Russian, "hello.world", goi18n.Vars{"name": "World"})
GetDefault(key string, vars Vars) string

Retrieves a translation for the default locale.

defaultTranslation := i18n.GetDefault("hello.world", goi18n.Vars{"name": "World"})
GetLocalizations(key string, vars Vars) *map[discordgo.Locale]string

Retrieves all loaded translations for the specified key.

localizations := i18n.GetLocalizations("hello.world", goi18n.Vars{"name": "World"})
for locale, translation := range *localizations {
    fmt.Printf("%s: %s\n", locale, translation)
}

Testing

To test the package, create JSON files for different locales (e.g., locales/ru.json, locales/en.json, locales/de.json) and run the tests using Go's testing framework.

Example test:

package goi18n

import (
	"github.com/bwmarrin/discordgo"
	"testing"
)

func TestGetTranslationsForMultipleLocales(t *testing.T) {
	i18n := NewLanguageI18N()

	// Load translation files
	err := i18n.LoadBundle(discordgo.Russian, "locales/ru.json")
	if err != nil {
		t.Fatalf("Failed to load Russian bundle: %v", err)
	}
	err = i18n.LoadBundle(discordgo.EnglishUS, "locales/en.json")
	if err != nil {
		t.Fatalf("Failed to load English bundle: %v", err)
	}

	// Set default language
	i18n.SetDefault(discordgo.EnglishUS)

	// Test translations
	tests := []struct {
		locale  discordgo.Locale
		key     string
		vars    goi18n.Vars
		wantAny []string
	}{
		{discordgo.Russian, "hello.world", goi18n.Vars{"name": "World"}, []string{"Привет, World!"}},
		{discordgo.EnglishUS, "hello.world", goi18n.Vars{"name": "World"}, []string{"Hello, World!"}},
	}

	for _, tt := range tests {
		got := i18n.Get(tt.locale, tt.key, tt.vars)
		found := false
		for _, expected := range tt.wantAny {
			if got == expected {
				found = true
				break
			}
		}
		if !found {
			t.Errorf("Get(%s, %s, %v): expected one of '%v', but got '%s'", tt.locale, tt.key, tt.vars, tt.wantAny, got)
		}
	}
}

Run the tests using:

go test ./...

Contributing

Contributions are welcome! Please open an issue or submit a pull request if you'd like to contribute improvements or fixes.


License

This project is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type LanguageI18N

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

LanguageI18N is the main struct for handling translations.

func NewLanguageI18N

func NewLanguageI18N() *LanguageI18N

NewLanguageI18N creates a new instance of LanguageI18N.

func (*LanguageI18N) Get

func (l *LanguageI18N) Get(locale discordgo.Locale, key string, variables Vars) string

Get gets a translation corresponding to a locale and a key.

func (*LanguageI18N) GetDefault

func (l *LanguageI18N) GetDefault(key string, variables Vars) string

GetDefault gets a translation corresponding to the default locale and a key.

func (*LanguageI18N) GetLocalizations

func (l *LanguageI18N) GetLocalizations(key string, variables Vars) *map[discordgo.Locale]string

GetLocalizations retrieves translations from every loaded bundle.

func (*LanguageI18N) LoadBundle

func (l *LanguageI18N) LoadBundle(locale discordgo.Locale, path string) error

LoadBundle loads a translation file corresponding to a specified locale.

func (*LanguageI18N) SetDefault

func (l *LanguageI18N) SetDefault(language discordgo.Locale)

SetDefault sets the locale used as a fallback.

type Vars

type Vars map[string]interface{}

Vars represents a map of variables to be injected into translations.

Jump to

Keyboard shortcuts

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