Help us shape the future of Go! Take the 2026 Go Developer Survey

gotext

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2026 License: BSD-3-Clause, MIT Imports: 15 Imported by: 397

README

GitHub release MIT license Gotext build Go Report Card PkgGoDev

Gotext

GNU gettext utilities for Go.

gotext is a native Go implementation of the GNU Gettext utilities. It provides a thread-safe, flexible, and powerful way to handle internationalization (i18n) and localization (l10n) in your Go applications.


📖 Read the Full Documentation


Table of Contents

Features

  • Native Go implementation of Gettext (the core library has no external dependencies).
  • Full support for PO and MO files.
  • Pluralization rules support via GNU Gettext plural-form expressions.
  • Message context support (msgctxt).
  • Thread-safe for concurrent use.
  • Works with UTF-8 by default.
  • Integrated CLI tool (xgotext) for string extraction.
  • Serializable objects for caching.
  • Plain-string results that plug directly into Go's text/template and html/template pipelines.

Installation

go get github.com/leonelquinteros/gotext

Getting Started

For a quick start, use the package-level API:

package main

import (
    "fmt"
    "github.com/leonelquinteros/gotext"
)

func main() {
    // Configure package: locales path, language, and domain
    gotext.Configure("/path/to/locales", "en_US", "default")

    // Simple translation
    fmt.Println(gotext.Get("Hello, world!"))

    // Translation with variables
    fmt.Println(gotext.Get("Hello, %s!", "Gopher"))
}

For more details, see the Getting Started Guide.


CLI Tool (xgotext)

gotext includes a command-line tool to extract translatable strings from your Go source code.

Install xgotext:

go install github.com/leonelquinteros/gotext/cli/xgotext@latest

Extract strings:

xgotext -in . -out locales/templates

The command generates .pot templates under locales/templates; merge those templates into language-specific .po files.

See the xgotext Documentation for full usage details.


Advanced Usage

Using Locale object

For managing multiple languages or domains independently:

l := gotext.NewLocale("/path/to/locales", "es_UY")
l.AddDomain("default")
fmt.Println(l.Get("Translate this"))
Use plural forms of translations

gotext handles complex pluralization rules defined in PO headers:

// GetN(singular, plural, quantity, args...)
fmt.Println(gotext.GetN("I have one apple.", "I have %d apples.", 5, 5))

See the Plural Forms Guide for more examples.

Using dynamic variables on translations

Supports standard fmt package syntax:

name := "John"
fmt.Println(gotext.Get("Hi, my name is %s", name))
More advanced scenarios
  • Embedded translation files (embed.FS) and named %(name)s formatting: see the Advanced Usage Guide.
  • Languages fallback: pass multiple languages to Configure as a colon-separated list (gotext.Configure("/path/to/locales", "es_UY:es:en_US", "default")).
  • Serialization/caching of parsed locales: Locale.MarshalBinary / UnmarshalBinary.

Locales directories structure

The package expects a standard Gettext directory structure:

/path/to/locales
  /en_US
    /LC_MESSAGES
      default.po
  /es_ES
    /LC_MESSAGES
      default.po

Translation files can live either inside an LC_MESSAGES subdirectory or directly under the language code (/es_ES/default.po); both layouts are supported.

It supports automatic language simplification (e.g., falling back from en_UK to en).


Contributing

We welcome contributions of all kinds!


License

gotext is released under the MIT License.

Documentation

Overview

Package gotext implements GNU gettext utilities.

For quick/simple translations you can use the package level functions directly.

    import (
	    "fmt"
	    "github.com/leonelquinteros/gotext"
    )

    func main() {
        // Configure package
        gotext.Configure("/path/to/locales/root/dir", "en_UK", "domain-name")

        // Translate text from default domain
        fmt.Println(gotext.Get("My text on 'domain-name' domain"))

        // Translate text from a different domain without reconfigure
        fmt.Println(gotext.GetD("domain2", "Another text on a different domain"))
    }

Index

Constants

View Source
const (
	// MoMagicLittleEndian encoding
	MoMagicLittleEndian = 0x950412de
	// MoMagicBigEndian encoding
	MoMagicBigEndian = 0xde120495

	// EotSeparator msgctxt and msgid separator
	EotSeparator = "\x04"
	// NulSeparator msgid and msgstr separator
	NulSeparator = "\x00"
)

Variables

View Source
var FallbackLocale = "en_US"

FallbackLocale is the default language to be used when no language is set.

Functions

func Appendf added in v1.7.0

func Appendf(b []byte, str string, vars ...any) []byte

Appendf applies text formatting only when needed to parse variables.

func Configure

func Configure(lib, lang, dom string)

Configure sets all configuration variables to be used at package level and reloads the corresponding Translation file. It receives the library path, language code and domain name. This function is recommended to be used when changing more than one setting, as using each setter will introduce a I/O overhead because the Translation file will be loaded after each set.

func EscapeSpecialCharacters added in v1.5.1

func EscapeSpecialCharacters(s string) string

EscapeSpecialCharacters escapes special characters in a string

func FormatString added in v1.7.2

func FormatString(str string, vars ...any) string

FormatString applies text formatting only when needed to parse variables.

func FormatStringWithArgs added in v1.8.0

func FormatStringWithArgs(str string, vars []any) string

FormatStringWithArgs applies text formatting as a proxy for fmt.Sprintf.

func Get

func Get(str string, vars ...any) string

Get uses the default domain globally set to return the corresponding Translation of a given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func GetC added in v1.0.0

func GetC(str, ctx string, vars ...any) string

GetC uses the default domain globally set to return the corresponding Translation of the given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func GetD

func GetD(dom, str string, vars ...any) string

GetD returns the corresponding Translation in the given domain for a given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func GetDC added in v1.0.0

func GetDC(dom, str, ctx string, vars ...any) string

GetDC returns the corresponding Translation in the given domain for the given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func GetDomain

func GetDomain() string

GetDomain is the domain getter for the package configuration

func GetLanguage

func GetLanguage() string

GetLanguage returns the language gotext will translate into. If multiple languages have been supplied, the first one will be returned. If no language has been supplied, the fallback will be returned.

func GetLanguages added in v1.6.0

func GetLanguages() []string

GetLanguages returns all languages that have been supplied.

func GetLibrary

func GetLibrary() string

GetLibrary is the library getter for the package configuration

func GetN

func GetN(str, plural string, n int, vars ...any) string

GetN retrieves the (N)th plural form of Translation for the given string in the default domain. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func GetNC added in v1.0.0

func GetNC(str, plural string, n int, ctx string, vars ...any) string

GetNC retrieves the (N)th plural form of Translation for the given string in the given context in the default domain. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func GetND

func GetND(dom, str, plural string, n int, vars ...any) string

GetND retrieves the (N)th plural form of Translation in the given domain for a given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func GetNDC added in v1.0.0

func GetNDC(dom, str, plural string, n int, ctx string, vars ...any) string

GetNDC retrieves the (N)th plural form of Translation in the given domain for a given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func IsTranslated added in v1.6.0

func IsTranslated(str string, langs ...string) bool

IsTranslated reports whether a string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedC added in v1.6.0

func IsTranslatedC(str, ctx string, langs ...string) bool

IsTranslatedC reports whether a context string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedD added in v1.6.0

func IsTranslatedD(dom, str string, langs ...string) bool

IsTranslatedD reports whether a domain string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedDC added in v1.6.0

func IsTranslatedDC(dom, str, ctx string, langs ...string) bool

IsTranslatedDC reports whether a domain context string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedN added in v1.6.0

func IsTranslatedN(str string, n int, langs ...string) bool

IsTranslatedN reports whether a plural string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedNC added in v1.6.0

func IsTranslatedNC(str string, n int, ctx string, langs ...string) bool

IsTranslatedNC reports whether a plural context string is translated in given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedND added in v1.6.0

func IsTranslatedND(dom, str string, n int, langs ...string) bool

IsTranslatedND reports whether a plural domain string is translated in any of given languages. When the langs argument is omitted, the output of GetLanguages is used.

func IsTranslatedNDC added in v1.6.0

func IsTranslatedNDC(dom, str string, n int, ctx string, langs ...string) bool

IsTranslatedNDC reports whether a plural domain context string is translated in any of given languages. When the langs argument is omitted, the output of GetLanguages is used.

func NPrintf added in v1.4.0

func NPrintf(format string, params map[string]any)

NPrintf support named format NPrintf("%(name)s is Type %(type)s", map[string]any{"name": "Gotext", "type": "struct"})

func SetDomain

func SetDomain(dom string)

SetDomain sets the name for the domain to be used at package level. It reloads the corresponding Translation file.

func SetLanguage

func SetLanguage(lang string)

SetLanguage sets the language code (or colon separated language codes) to be used at package level. It reloads the corresponding Translation file.

func SetLibrary

func SetLibrary(lib string)

SetLibrary sets the root path for the locale directories and files to be used at package level. It reloads the corresponding Translation file.

func SetLocales added in v1.6.0

func SetLocales(locales []*Locale)

SetLocales allows for overriding the global Locale objects with ones built manually with NewLocale(). This makes it possible to attach custom Domain objects from in-memory po/mo. The library, language and domain of the first Locale will set the default global configuration.

func SetStorage deprecated added in v1.6.0

func SetStorage(locale *Locale)

SetStorage allows overriding the global Locale object with one built manually with NewLocale().

Deprecated: Storage has been renamed to Locale for consistency, use SetLocales instead.

func SimplifiedLocale added in v1.4.0

func SimplifiedLocale(lang string) string

SimplifiedLocale simplified locale like " en_US"/"de_DE "/en_US.UTF-8/zh_CN/zh_TW/el_GR@euro/... to en_US, de_DE, zh_CN, el_GR...

func Sprintf added in v1.4.0

func Sprintf(format string, params map[string]any) string

Sprintf support named format

Sprintf("%(name)s is Type %(type)s", map[string]any{"name": "Gotext", "type": "struct"})

Types

type AppendTranslator added in v1.7.0

type AppendTranslator interface {
	Translator
	Append(b []byte, str string, vars ...any) []byte
	AppendN(b []byte, str, plural string, n int, vars ...any) []byte
	AppendC(b []byte, str, ctx string, vars ...any) []byte
	AppendNC(b []byte, str, plural string, n int, ctx string, vars ...any) []byte
}

AppendTranslator interface is used by Locale and Po objects. It contains all methods needed to parse translation sources and to append entries to the object.

type Domain added in v1.5.0

type Domain struct {
	Headers HeaderMap

	// Language header
	Language string

	// Plural-Forms header
	PluralForms string
	// contains filtered or unexported fields
}

Domain has all the common functions for dealing with a gettext domain it's initialized with a GettextFile (which represents either a Po or Mo file)

func NewDomain added in v1.5.0

func NewDomain() *Domain

NewDomain creates a new Domain instance

func (*Domain) Append added in v1.7.0

func (do *Domain) Append(b []byte, str string, vars ...any) []byte

Append retrieves the Translation for the given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) AppendC added in v1.7.0

func (do *Domain) AppendC(b []byte, str, ctx string, vars ...any) []byte

AppendC retrieves the corresponding Translation for a given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) AppendN added in v1.7.0

func (do *Domain) AppendN(b []byte, str, plural string, n int, vars ...any) []byte

AppendN adds the (N)th plural form of Translation for the given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) AppendNC added in v1.7.0

func (do *Domain) AppendNC(b []byte, str, plural string, n int, ctx string, vars ...any) []byte

AppendNC retrieves the (N)th plural form of Translation for the given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) DropStaleTranslations added in v1.5.0

func (do *Domain) DropStaleTranslations()

DropStaleTranslations drops any translations stored that have not been Set*() since 'po' was initialised

func (*Domain) Get added in v1.5.0

func (do *Domain) Get(str string, vars ...any) string

Get retrieves the Translation for the given string.

func (*Domain) GetC added in v1.5.0

func (do *Domain) GetC(str, ctx string, vars ...any) string

GetC retrieves the corresponding Translation for a given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) GetCtxTranslations added in v1.7.2

func (do *Domain) GetCtxTranslations() map[string]map[string]*Translation

GetCtxTranslations returns a copy of every translation in the domain with context

func (*Domain) GetN added in v1.5.0

func (do *Domain) GetN(str, plural string, n int, vars ...any) string

GetN retrieves the (N)th plural form of Translation for the given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) GetNC added in v1.5.0

func (do *Domain) GetNC(str, plural string, n int, ctx string, vars ...any) string

GetNC retrieves the (N)th plural form of Translation for the given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Domain) GetRefs added in v1.5.0

func (do *Domain) GetRefs(str string) []string

GetRefs get source references for a given translation

func (*Domain) GetTranslations added in v1.5.0

func (do *Domain) GetTranslations() map[string]*Translation

GetTranslations returns a copy of every translation in the domain. It does not support contexts.

func (*Domain) IsTranslated added in v1.6.0

func (do *Domain) IsTranslated(str string) bool

IsTranslated reports whether a string is translated

func (*Domain) IsTranslatedC added in v1.6.0

func (do *Domain) IsTranslatedC(str, ctx string) bool

IsTranslatedC reports whether a context string is translated

func (*Domain) IsTranslatedN added in v1.6.0

func (do *Domain) IsTranslatedN(str string, n int) bool

IsTranslatedN reports whether a plural string is translated

func (*Domain) IsTranslatedNC added in v1.6.0

func (do *Domain) IsTranslatedNC(str string, n int, ctx string) bool

IsTranslatedNC reports whether a plural context string is translated

func (*Domain) MarshalBinary added in v1.5.0

func (do *Domain) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding.BinaryMarshaler interface

func (*Domain) MarshalText added in v1.5.0

func (do *Domain) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler interface Assists round-trip of POT/PO content

func (*Domain) Set added in v1.5.0

func (do *Domain) Set(id, str string)

Set the translation of a given string

func (*Domain) SetC added in v1.5.0

func (do *Domain) SetC(id, ctx, str string)

SetC sets the translation for the given string in the given context

func (*Domain) SetN added in v1.5.0

func (do *Domain) SetN(id, plural string, n int, str string)

SetN sets the (N)th plural form for the given string

func (*Domain) SetNC added in v1.5.0

func (do *Domain) SetNC(id, plural, ctx string, n int, str string)

SetNC sets the (N)th plural form for the given string in the given context

func (*Domain) SetPluralResolver added in v1.7.0

func (do *Domain) SetPluralResolver(f func(int) int)

SetPluralResolver sets a custom plural resolver function

func (*Domain) SetRefs added in v1.5.0

func (do *Domain) SetRefs(str string, refs []string)

SetRefs set source references for a given translation

func (*Domain) UnmarshalBinary added in v1.5.0

func (do *Domain) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler interface

type HeaderMap added in v1.5.0

type HeaderMap map[string][]string

HeaderMap preserves MIMEHeader behaviour, without the canonicalisation

func (HeaderMap) Add added in v1.5.0

func (m HeaderMap) Add(key, value string)

Add key/value pair to HeaderMap

func (HeaderMap) Del added in v1.5.0

func (m HeaderMap) Del(key string)

Del key from HeaderMap

func (HeaderMap) Get added in v1.5.0

func (m HeaderMap) Get(key string) string

Get value for key from HeaderMap

func (HeaderMap) Set added in v1.5.0

func (m HeaderMap) Set(key, value string)

Set key/value pair in HeaderMap

func (HeaderMap) Values added in v1.5.0

func (m HeaderMap) Values(key string) []string

Values returns all values for a given key from HeaderMap

type IsTranslatedDomainIntrospector added in v1.6.0

type IsTranslatedDomainIntrospector interface {
	IsTranslated(str string) bool
	IsTranslatedN(str string, n int) bool
	IsTranslatedD(dom, str string) bool
	IsTranslatedND(dom, str string, n int) bool
	IsTranslatedC(str, ctx string) bool
	IsTranslatedNC(str string, n int, ctx string) bool
	IsTranslatedDC(dom, str, ctx string) bool
	IsTranslatedNDC(dom, str string, n int, ctx string) bool
}

IsTranslatedDomainIntrospector is able to determine whether a given string is translated. Example of this introspector is Locale, which holds multiple domains. Simpler objects that are domain-specific, like Po or Mo, implement IsTranslatedIntrospector.

type IsTranslatedIntrospector added in v1.6.0

type IsTranslatedIntrospector interface {
	IsTranslated(str string) bool
	IsTranslatedN(str string, n int) bool
	IsTranslatedC(str, ctx string) bool
	IsTranslatedNC(str string, n int, ctx string) bool
}

IsTranslatedIntrospector is able to determine whether a given string is translated. Examples of this introspector are Po and Mo, which are specific to their domain. Locale holds multiple domains and also implements IsTranslatedDomainIntrospector.

type Locale

type Locale struct {

	// List of available Domains for this locale.
	Domains map[string]Translator

	// Sync Mutex
	sync.RWMutex
	// contains filtered or unexported fields
}

Locale wraps the entire i18n collection for a single language (locale) It's used by the package functions, but it can also be used independently to handle multiple languages at the same time by working with this object.

Example:

    import (
	    "fmt"
	    "github.com/leonelquinteros/gotext"
    )

    func main() {
        // Create Locale with library path and language code
        l := gotext.NewLocale("/path/to/i18n/dir", "en_US")

        // Load domain '/path/to/i18n/dir/en_US/LC_MESSAGES/default.{po,mo}'
        l.AddDomain("default")

        // Translate text from default domain
        fmt.Println(l.Get("Translate this"))

        // Load different domain ('/path/to/i18n/dir/en_US/LC_MESSAGES/extras.{po,mo}')
        l.AddDomain("extras")

        // Translate text from domain
        fmt.Println(l.GetD("extras", "Translate this"))
    }

func GetLocales added in v1.6.0

func GetLocales() []*Locale

GetLocales returns the locales that have been set for the package configuration.

func GetStorage deprecated added in v1.6.0

func GetStorage() *Locale

GetStorage is the locale storage getter for the package configuration.

Deprecated: Storage has been renamed to Locale for consistency, use GetLocales instead.

func NewLocale

func NewLocale(p, l string) *Locale

NewLocale creates and initializes a new Locale object for a given language. It receives a path for the i18n .po/.mo files directory (p) and a language code to use (l).

func NewLocaleFS added in v1.6.0

func NewLocaleFS(l string, filesystem fs.FS) *Locale

NewLocaleFS returns a Locale working with a fs.FS

func NewLocaleFSWithPath added in v1.7.0

func NewLocaleFSWithPath(l string, filesystem fs.FS, p string) *Locale

NewLocaleFSWithPath returns a Locale working with a fs.FS on a p path folder.

func (*Locale) AddDomain

func (l *Locale) AddDomain(dom string)

AddDomain creates a new domain for a given locale object and initializes the Po object. If the domain exists, it gets reloaded.

func (*Locale) AddTranslator added in v1.4.0

func (l *Locale) AddTranslator(dom string, tr Translator)

AddTranslator takes a domain name and a Translator object to make it available in the Locale object.

func (*Locale) Get

func (l *Locale) Get(str string, vars ...any) string

Get uses a domain "default" to return the corresponding Translation of a given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetActualLanguage added in v1.6.0

func (l *Locale) GetActualLanguage(dom string) string

GetActualLanguage inspects the filesystem and decides whether to strip a CC part of the ll_CC locale string.

func (*Locale) GetC added in v1.0.0

func (l *Locale) GetC(str, ctx string, vars ...any) string

GetC uses a domain "default" to return the corresponding Translation of the given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetD

func (l *Locale) GetD(dom, str string, vars ...any) string

GetD returns the corresponding Translation in the given domain for the given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetDC added in v1.0.0

func (l *Locale) GetDC(dom, str, ctx string, vars ...any) string

GetDC returns the corresponding Translation in the given domain for the given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetDomain added in v1.4.0

func (l *Locale) GetDomain() string

GetDomain is the domain getter for Locale configuration

func (*Locale) GetLanguage added in v1.6.0

func (l *Locale) GetLanguage() string

GetLanguage is the lang getter for Locale configuration

func (*Locale) GetN

func (l *Locale) GetN(str, plural string, n int, vars ...any) string

GetN retrieves the (N)th plural form of Translation for the given string in the "default" domain. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetNC added in v1.0.0

func (l *Locale) GetNC(str, plural string, n int, ctx string, vars ...any) string

GetNC retrieves the (N)th plural form of Translation for the given string in the given context in the "default" domain. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetND

func (l *Locale) GetND(dom, str, plural string, n int, vars ...any) string

GetND retrieves the (N)th plural form of Translation in the given domain for the given string. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetNDC added in v1.0.0

func (l *Locale) GetNDC(dom, str, plural string, n int, ctx string, vars ...any) string

GetNDC retrieves the (N)th plural form of Translation in the given domain for the given string in the given context. Supports optional parameters (vars... any) to be inserted on the formatted string using the fmt.Printf syntax.

func (*Locale) GetTranslations added in v1.5.0

func (l *Locale) GetTranslations() map[string]*Translation

GetTranslations returns a copy of all translations in all domains of this locale. It does not support contexts.

func (*Locale) IsTranslated added in v1.6.0

func (l *Locale) IsTranslated(str string) bool

IsTranslated reports whether a string is translated

func (*Locale) IsTranslatedC added in v1.6.0

func (l *Locale) IsTranslatedC(str, ctx string) bool

IsTranslatedC reports whether a context string is translated

func (*Locale) IsTranslatedD added in v1.6.0

func (l *Locale) IsTranslatedD(dom, str string) bool

IsTranslatedD reports whether a domain string is translated

func (*Locale) IsTranslatedDC added in v1.6.0

func (l *Locale) IsTranslatedDC(dom, str, ctx string) bool

IsTranslatedDC reports whether a domain context string is translated

func (*Locale) IsTranslatedN added in v1.6.0

func (l *Locale) IsTranslatedN(str string, n int) bool

IsTranslatedN reports whether a plural string is translated

func (*Locale) IsTranslatedNC added in v1.6.0

func (l *Locale) IsTranslatedNC(str string, n int, ctx string) bool

IsTranslatedNC reports whether a plural context string is translated

func (*Locale) IsTranslatedND added in v1.6.0

func (l *Locale) IsTranslatedND(dom, str string, n int) bool

IsTranslatedND reports whether a plural domain string is translated

func (*Locale) IsTranslatedNDC added in v1.6.0

func (l *Locale) IsTranslatedNDC(dom string, str string, n int, ctx string) bool

IsTranslatedNDC reports whether a plural domain context string is translated

func (*Locale) MarshalBinary added in v1.4.0

func (l *Locale) MarshalBinary() ([]byte, error)

MarshalBinary implements encoding BinaryMarshaler interface

func (*Locale) SetDomain added in v1.4.0

func (l *Locale) SetDomain(dom string)

SetDomain sets the name for the domain to be used.

func (*Locale) UnmarshalBinary added in v1.4.0

func (l *Locale) UnmarshalBinary(data []byte) error

UnmarshalBinary implements encoding.BinaryUnmarshaler interface

type LocaleEncoding added in v1.4.0

type LocaleEncoding struct {
	Path          string
	Lang          string
	Domains       map[string][]byte
	DefaultDomain string
}

LocaleEncoding is used as intermediary storage to encode Locale objects to Gob.

type Mo added in v1.4.0

type Mo struct {
	// these three public members are for backwards compatibility. they are just set to the value in the domain
	Headers     HeaderMap
	Language    string
	PluralForms string
	// contains filtered or unexported fields
}

Mo parses the content of any MO file and provides all the Translation functions needed. It's the base object used by all package methods. And it's safe for concurrent use by multiple goroutines by using the sync package for locking.

Example:

import (
	"fmt"
	"github.com/leonelquinteros/gotext"
)

func main() {
	// Create mo object
	mo := gotext.NewMo()

	// Parse .mo file
	mo.ParseFile("/path/to/po/file/translations.mo")

	// Get Translation
	fmt.Println(mo.Get("Translate this"))
}

func NewMo added in v1.5.0

func NewMo() *Mo

NewMo should always be used to instantiate a new Mo object

func NewMoFS added in v1.6.0

func NewMoFS(filesystem fs.FS) *Mo

NewMoFS works like NewMO but adds an optional fs.FS

func (*Mo) Append added in v1.7.0

func (mo *Mo) Append(b []byte, str string, vars ...any) []byte

Append a translation string into the domain

func (*Mo) AppendC added in v1.7.0

func (mo *Mo) AppendC(b []byte, str, ctx string, vars ...any) []byte

AppendC appends a translation string for the given context into the domain

func (*Mo) AppendN added in v1.7.0

func (mo *Mo) AppendN(b []byte, str, plural string, n int, vars ...any) []byte

AppendN appends a translation string for the given plural form into the domain

func (*Mo) AppendNC added in v1.7.0

func (mo *Mo) AppendNC(b []byte, str, plural string, n int, ctx string, vars ...any) []byte

AppendNC appends a translation string for the given plural form and context into the domain

func (*Mo) Get added in v1.4.0

func (mo *Mo) Get(str string, vars ...any) string

Get returns the translation for the given string

func (*Mo) GetC added in v1.4.0

func (mo *Mo) GetC(str, ctx string, vars ...any) string

GetC returns the translation for the given string and context

func (*Mo) GetDomain added in v1.5.0

func (mo *Mo) GetDomain() *Domain

GetDomain returns the domain object

func (*Mo) GetN added in v1.4.0

func (mo *Mo) GetN(str, plural string, n int, vars ...any) string

GetN returns the translation for the given string and plural form

func (*Mo) GetNC added in v1.4.0

func (mo *Mo) GetNC(str, plural string, n int, ctx string, vars ...any) string

GetNC returns the translation for the given string, plural form and context

func (*Mo) IsTranslated added in v1.6.0

func (mo *Mo) IsTranslated(str string) bool

IsTranslated checks if the given string is translated

func (*Mo) IsTranslatedC added in v1.6.0

func (mo *Mo) IsTranslatedC(str, ctx string) bool

IsTranslatedC checks if the given string is translated with context

func (*Mo) IsTranslatedN added in v1.6.0

func (mo *Mo) IsTranslatedN(str string, n int) bool

IsTranslatedN checks if the given string is translated with plural form

func (*Mo) IsTranslatedNC added in v1.6.0

func (mo *Mo) IsTranslatedNC(str string, n int, ctx string) bool

IsTranslatedNC checks if the given string is translated with plural form and context

func (*Mo) MarshalBinary added in v1.4.0

func (mo *Mo) MarshalBinary() ([]byte, error)

MarshalBinary marshals the Mo object into a binary format

func (*Mo) Parse added in v1.4.0

func (mo *Mo) Parse(buf []byte)

Parse loads the translations specified in the provided byte slice, in the GNU gettext .mo format

func (*Mo) ParseFile added in v1.4.0

func (mo *Mo) ParseFile(f string)

ParseFile loads the translations specified in the provided file, in the GNU gettext .mo format

func (*Mo) UnmarshalBinary added in v1.4.0

func (mo *Mo) UnmarshalBinary(data []byte) error

UnmarshalBinary unmarshals the Mo object from a binary format

type Po

type Po struct {
	// these three public members are for backwards compatibility. they are just set to the value in the domain
	Headers     HeaderMap
	Language    string
	PluralForms string
	// contains filtered or unexported fields
}

Po parses the content of any PO file and provides all the Translation functions needed. It's the base object used by all package methods. And it's safe for concurrent use by multiple goroutines by using the sync package for locking.

Example:

import (
	"fmt"
	"github.com/leonelquinteros/gotext"
)

func main() {
	// Create po object
	po := gotext.NewPo()

	// Parse .po file
	po.ParseFile("/path/to/po/file/translations.po")

	// Get Translation
	fmt.Println(po.Get("Translate this"))
}

func NewPo added in v1.5.0

func NewPo() *Po

NewPo should always be used to instantiate a new Po object

func NewPoFS added in v1.6.0

func NewPoFS(filesystem fs.FS) *Po

NewPoFS works like NewPO but adds an optional fs.FS

func (*Po) Append added in v1.7.0

func (po *Po) Append(b []byte, str string, vars ...any) []byte

Append translation

func (*Po) AppendC added in v1.7.0

func (po *Po) AppendC(b []byte, str, ctx string, vars ...any) []byte

AppendC appends the translation for a given context

func (*Po) AppendN added in v1.7.0

func (po *Po) AppendN(b []byte, str, plural string, n int, vars ...any) []byte

AppendN appends the plural translation

func (*Po) AppendNC added in v1.7.0

func (po *Po) AppendNC(b []byte, str, plural string, n int, ctx string, vars ...any) []byte

AppendNC appends the plural translation for a given context

func (*Po) DropStaleTranslations added in v1.5.0

func (po *Po) DropStaleTranslations()

DropStaleTranslations removes all translations that are not referenced in the current domain

func (*Po) Get

func (po *Po) Get(str string, vars ...any) string

Get translation

func (*Po) GetC added in v1.0.0

func (po *Po) GetC(str, ctx string, vars ...any) string

GetC gets the translation for a given context

func (*Po) GetDomain added in v1.5.0

func (po *Po) GetDomain() *Domain

GetDomain returns the domain object

func (*Po) GetN

func (po *Po) GetN(str, plural string, n int, vars ...any) string

GetN gets the plural translation

func (*Po) GetNC added in v1.0.0

func (po *Po) GetNC(str, plural string, n int, ctx string, vars ...any) string

GetNC gets the plural translation for a given context

func (*Po) GetRefs added in v1.5.0

func (po *Po) GetRefs(str string) []string

GetRefs returns the references for a given translation

func (*Po) IsTranslated added in v1.6.0

func (po *Po) IsTranslated(str string) bool

IsTranslated checks if the given string is translated

func (*Po) IsTranslatedC added in v1.6.0

func (po *Po) IsTranslatedC(str, ctx string) bool

IsTranslatedC checks if the given string is translated with context

func (*Po) IsTranslatedN added in v1.6.0

func (po *Po) IsTranslatedN(str string, n int) bool

IsTranslatedN checks if the given string is translated with plural form

func (*Po) IsTranslatedNC added in v1.6.0

func (po *Po) IsTranslatedNC(str string, n int, ctx string) bool

IsTranslatedNC checks if the given string is translated with plural form and context

func (*Po) MarshalBinary added in v1.4.0

func (po *Po) MarshalBinary() ([]byte, error)

MarshalBinary marshals the Po object to binary

func (*Po) MarshalText added in v1.5.0

func (po *Po) MarshalText() ([]byte, error)

MarshalText marshals the Po object to text

func (*Po) Parse

func (po *Po) Parse(buf []byte)

Parse loads the translations specified in the provided byte slice (buf)

func (*Po) ParseFile

func (po *Po) ParseFile(f string)

ParseFile loads the translations from a file

func (*Po) Set added in v1.5.0

func (po *Po) Set(id, str string)

Set translation

func (*Po) SetC added in v1.5.0

func (po *Po) SetC(id, ctx, str string)

SetC sets the translation for a given context

func (*Po) SetN added in v1.5.0

func (po *Po) SetN(id, plural string, n int, str string)

SetN sets the plural translation

func (*Po) SetNC added in v1.5.0

func (po *Po) SetNC(id, plural, ctx string, n int, str string)

SetNC sets the plural translation for a given context

func (*Po) SetPluralResolver added in v1.7.0

func (po *Po) SetPluralResolver(f func(int) int)

SetPluralResolver sets the plural resolver function

func (*Po) SetRefs added in v1.5.0

func (po *Po) SetRefs(str string, refs []string)

SetRefs sets the references for a given translation

func (*Po) UnmarshalBinary added in v1.4.0

func (po *Po) UnmarshalBinary(data []byte) error

UnmarshalBinary unmarshals the Po object from binary

type SourceReference added in v1.5.0

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

SourceReference is a struct to hold source reference information

type Translation added in v1.4.0

type Translation struct {
	ID       string
	PluralID string
	Trs      map[int]string
	Refs     []string
	// contains filtered or unexported fields
}

Translation is the struct for the Translations parsed via Po or Mo files and all coming parsers

func NewTranslation added in v1.4.0

func NewTranslation() *Translation

NewTranslation returns the Translation object and initialized it.

func NewTranslationWithRefs added in v1.5.0

func NewTranslationWithRefs(refs []string) *Translation

NewTranslationWithRefs returns the Translation object and initialized it with references.

func (*Translation) Get added in v1.4.0

func (t *Translation) Get() string

Get returns the string of the translation

func (*Translation) GetN added in v1.4.0

func (t *Translation) GetN(n int) string

GetN returns the string of the plural translation

func (*Translation) IsStale added in v1.5.0

func (t *Translation) IsStale() bool

IsStale returns whether the translation is stale or not

func (*Translation) IsTranslated added in v1.6.0

func (t *Translation) IsTranslated() bool

IsTranslated reports whether a string is translated

func (*Translation) IsTranslatedN added in v1.6.0

func (t *Translation) IsTranslatedN(n int) bool

IsTranslatedN reports whether a plural string is translated

func (*Translation) Set added in v1.5.0

func (t *Translation) Set(str string)

Set sets the string of the translation

func (*Translation) SetN added in v1.5.0

func (t *Translation) SetN(n int, str string)

SetN sets the string of the plural translation

func (*Translation) SetRefs added in v1.5.0

func (t *Translation) SetRefs(refs []string)

SetRefs sets the references of the translation

type Translator added in v1.4.0

type Translator interface {
	ParseFile(f string)
	Parse(buf []byte)
	Get(str string, vars ...any) string
	GetN(str, plural string, n int, vars ...any) string
	GetC(str, ctx string, vars ...any) string
	GetNC(str, plural string, n int, ctx string, vars ...any) string

	MarshalBinary() ([]byte, error)
	UnmarshalBinary([]byte) error
	GetDomain() *Domain
}

Translator interface is used by Locale and Po objects. It contains all methods needed to parse translation sources and obtain corresponding translations. It includes encoding.BinaryMarshaler and encoding.BinaryUnmarshaler methods for Locale serialization.

type TranslatorEncoding added in v1.4.0

type TranslatorEncoding struct {
	// Headers storage
	Headers HeaderMap

	// Language header
	Language string

	// Plural-Forms header
	PluralForms string

	// Parsed Plural-Forms header values
	Nplurals int
	Plural   string

	// Storage
	Translations map[string]*Translation
	Contexts     map[string]map[string]*Translation
}

TranslatorEncoding is used as intermediary storage to encode Translator objects to Gob.

func (*TranslatorEncoding) GetTranslator added in v1.4.0

func (te *TranslatorEncoding) GetTranslator() Translator

GetTranslator is used to recover a Translator object after unmarshalling the TranslatorEncoding object. Internally uses a Po object as it should be switchable with Mo objects without problem. External Translator implementations should be able to serialize into a TranslatorEncoding object in order to deserialize into a Po-compatible object.

Directories

Path Synopsis
cli
xgotext command
Package plurals is the pluralform compiler to get the correct translation id of the plural string
Package plurals is the pluralform compiler to get the correct translation id of the plural string

Jump to

Keyboard shortcuts

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