Translator

This package provides a flexible translation system in Go, supporting multiple translation formats including YAML and PO files.

Static Badge

GoDoc GitHub stars Go Report Card codecov

Versions

Stable Version GitHub Release GitHub Release

Features

  • Support for multiple translation formats (YAML, PO/MO).
  • Thread-safe implementation with sync.RWMutex.
  • Supports hierarchical and nested keys for translations.
  • Easy registration of multiple translators.
  • Dynamic language switching.

Installation

go get -u github.com/gouef/translator

Usage

Initializing the Translator

package main

import (
	"fmt"
	"log"
	"github.com/gouef/translator"
)

func main() {
	translator.Init()

	// Load YAML translations
	yamlTranslator, err := translator.NewYaml("locales")
	if err != nil {
		log.Fatal(err)
	}
	translator.Register(yamlTranslator)

	// Set active language
	err = translator.SetLanguage("cs_CZ")
	if err != nil {
		log.Fatal(err)
	}

	// Translate a key
	fmt.Println(translator.Translate("hello"))
}

Using PO Translations

package main

import (
	"fmt"
	"log"
	"github.com/gouef/translator"
)

func main() {
	translator.Init()

	poTranslator, err := translator.NewPO("locales")
	if err != nil {
		log.Fatal(err)
	}
	translator.Register(poTranslator)

	err = translator.SetLanguage("cs_CZ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(translator.Translate("errors.hello"))
}

API Documentation

translator.Init()

Initializes the translator system by clearing registered translators.

translator.Register(translator Translator)

Registers a new translation provider (YAML, PO, etc.). The last registered provider becomes the active one.

translator.SetLanguage(lang string) error

Sets the active language for translation.

translator.GetLanguage() string

Returns the currently active language.

translator.Translate(key string, args ...interface{}) string

Translates a given key using the active translation provider. Supports placeholders with formatting.

YAML Format

Example locales/cs_CZ/messages.yaml:

hello: "Ahoj"
errors:
  hello: "Chyba: Ahoj"

PO/MO Format

Example locales/cs_CZ/messages.po:

msgid "hello"
msgstr "Ahoj"

msgid "errors.hello"
msgstr "Chyba: Ahoj"

Contributing

Read Contributing

Contributors

actions-user JanGalek

Join our Discord Community! 🎉

Discord

Click above to join our community on Discord!