i18n

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 26, 2025 License: MIT Imports: 8 Imported by: 0

README

go-i18n

Go Go Report Card codecov GoDoc Go Version License

go-i18n is a simple internationalization library for Go. This wraps nicksnyder/go-i18n and adds useful features for easier integration and customization.

Installation

go get -u github.com/afkdevs/go-i18n

Features

  • Support for translation files in YAML, JSON, and TOML formats
  • Simple string translation
  • Context-based translation
  • Parameterized translation
  • Fallback for missing translations
  • Customizable language extraction from context

Usage

Create Translation File

locales/en.yaml

hello: Hello
hello_name: Hello, {{.name}}
hello_name_age: Hello, {{.name}}. You are {{.age}} years old

locales/id.yaml

hello: Halo
hello_name: Halo, {{.name}}
hello_name_age: Halo, {{.name}}. Kamu berumur {{.age}} tahun
Initialize i18n
package main

import (
	"log"

	"github.com/afkdevs/go-i18n"
	"golang.org/x/text/language"
	"gopkg.in/yaml.v3"
)

func main() {
	err := i18n.Init(language.English,
		i18n.WithUnmarshalFunc("yaml", yaml.Unmarshal),
		i18n.WithTranslationFile("locales/en.yaml", "locales/id.yaml"),
	)
	if err != nil {
		log.Fatalf("failed to initialize i18n: %v", err)
	}
}
Translate your text
Simple translation
msg := i18n.T("hello")

// Or with a specific language
msg = i18n.T("hello", i18n.Lang("id"))
Translation with parameters
// Single parameter
msg := i18n.T("hello_name", i18n.Param("name", "John"))

// Multiple parameters
msg := i18n.T("hello_name_age", i18n.Params{
	"name": "John",
	"age":  20,
})

// Or using a map
msg := i18n.T("hello_name_age", map[string]any{
	"name": "John",
	"age":  20,
})

Context Translation

Use TCtx to translate using a context.Context, which is helpful for request-scoped translations.

Example with chi:

package main

import (
	"net/http"

	"github.com/afkdevs/go-i18n"
	"github.com/go-chi/chi/v5"
	"golang.org/x/text/language"
	"gopkg.in/yaml.v3"
)

func main() {
	if err := i18n.Init(language.English,
		i18n.WithUnmarshalFunc("yaml", yaml.Unmarshal),
		i18n.WithTranslationFile("locales/en.yaml", "locales/id.yaml"),
	); err != nil {
		panic(err)
	}

	r := chi.NewRouter()

	// Automatically inject language context
	r.Use(i18n.NewMiddleware())

	r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
		message := i18n.TCtx(r.Context(), "hello")
		_, _ = w.Write([]byte(message))
	})
	r.Get("/hello/{name}", func(w http.ResponseWriter, r *http.Request) {
		name := chi.URLParam(r, "name")
		message := i18n.TCtx(r.Context(), "hello_name", i18n.Params{"name": name})
		_, _ = w.Write([]byte(message))
	})

	http.ListenAndServe(":3000", r)
}

Fallback for Missing Translations

You can set a global configuration for missing translations by using i18n.WithMissingTranslationHandler when initializing i18n.

package main

import (
	"fmt"
	"log"

	"github.com/afkdevs/go-i18n"
	"golang.org/x/text/language"
	"gopkg.in/yaml.v3"
)

func main() {
	if err := i18n.Init(language.English,
		i18n.WithUnmarshalFunc("yaml", yaml.Unmarshal),
		i18n.WithTranslationFile("locales/en.yaml", "locales/id.yaml"),
		i18n.WithMissingTranslationHandler(missingTranslationHandler),
	); err != nil {
		panic(err)
	}
}

func missingTranslationHandler(id string, _ error) string {
	return fmt.Sprintf("ERROR: missing translation for %q", id)
}

Contributing

Contributions are welcome!
If you’d like to make major changes, please open an issue first to discuss your ideas.

License

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

Documentation

Overview

Package i18n is a wrapper for go-i18n. It provides a simple API to localize your application.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(id string, opts ...any) string

Get returns the translated message for the given message id.

It uses the default language tag.

Example:

message := i18n.Get("hello", i18n.Params{"name": "John"})

func GetCtx

func GetCtx(ctx context.Context, id string, opts ...any) string

GetCtx returns the translated message for the given message id.

It uses the language from the context. You can set the language to the context with i18n.Middleware. If the language is not found in the context, it uses the default language tag.

Example:

message := i18n.GetCtx(ctx, "hello", i18n.Params{"name": "John"})

func GetLanguage

func GetLanguage(ctx context.Context) language.Tag

GetLanguage returns the language tag from the context.

If the language tag is not found, it returns the default language tag.

func Init

func Init(language language.Tag, opts ...Option) error

Init initializes the i18n package. It must be called before any other function.

Example:

if err := i18n.Init(language.English,
	i18n.WithUnmarshalFunc("yaml", yaml.Unmarshal),
	i18n.WithMessageFilePaths("locales/en.yaml", "locales/id.yaml"),
) err != nil {
	panic(err)
}

func NewMiddleware added in v0.2.1

func NewMiddleware(opts ...MiddlewareOption) func(http.Handler) http.Handler

NewMiddleware creates a middleware that sets the language to the context from the request.

It uses the Accept-Language header to get the language.

func SetLangToContext added in v0.2.1

func SetLangToContext(ctx context.Context, language string) context.Context

SetLangToContext sets the language to the context.

You can use this function to set the language to the context manually.

func T

func T(id string, opts ...any) string

T is an alias for Get.

Example:

message := i18n.T("hello", i18n.Params{"name": "John"})

func TCtx

func TCtx(ctx context.Context, id string, opts ...any) string

TCtx is an alias for GetCtx.

Example:

message := i18n.TCtx(ctx, "hello", i18n.Params{"name": "John"})

Types

type LocalizeOption

type LocalizeOption func(*localizeConfig)

LocalizeOption is a function that configures the localizeConfig.

func Default

func Default(defaultMessage string) LocalizeOption

Default sets the default message for the message.

It is used when the message is not found.

Example:

i18n.T("hello", i18n.Default("Hello, {{.name}}!"), i18n.Param("name", "John")))

func Lang

func Lang(language string) LocalizeOption

Lang sets the language for the message.

Example:

i18n.T("hello", i18n.Lang("id"))

func Param

func Param(key string, value any) LocalizeOption

Param set single value of template data for the message.

Example:

i18n.T("hello", i18n.Param("name", "John"))

type MiddlewareOption added in v0.2.1

type MiddlewareOption func(*middlewareConfig)

MiddlewareOption is a function that configures the middleware.

func WithHeaderKey added in v0.2.1

func WithHeaderKey(key string) MiddlewareOption

WithHeaderKey sets the header key for the middleware.

func WithLanguageHandler added in v0.2.1

func WithLanguageHandler(handler func(r *http.Request) string) MiddlewareOption

WithLanguageHandler sets the language handler for the middleware.

type Option

type Option func(*config)

Option is the option for the i18n package.

func WithExtractLanguageFunc

func WithExtractLanguageFunc(extractLanguageFunc func(ctx context.Context) string) Option

WithExtractLanguageFunc sets the language extract function for the middleware.

It is used to extract the language from the context.

func WithMissingTranslationHandler

func WithMissingTranslationHandler(missingTranslationHandler func(id string, err error) string) Option

WithMissingTranslationHandler sets the missing translation handler for the bundle.

It is used to handle the missing translation. The default handler returns the message ID.

func WithTranslationFSFile

func WithTranslationFSFile(fs embed.FS, paths ...string) Option

WithTranslationFSFile sets the message file paths for the bundle.

It is similar to WithTranslationFile, but it uses embed.FS as file system.

func WithTranslationFile

func WithTranslationFile(paths ...string) Option

WithTranslationFile sets the message file paths for the bundle.

func WithUnmarshalFunc

func WithUnmarshalFunc(format string, unmarshalFunc i18n.UnmarshalFunc) Option

WithUnmarshalFunc sets the unmarshal function for the bundle.

It is used to unmarshal the message file. You can use yaml.Unmarshal, json.Unmarshal, or any other unmarshal function.

type Params

type Params map[string]any

Params is an alias for map[string]any. It is used to set template data for the message.

Example:

i18n.T("hello", i18n.Params{"name": "John", "age": 30})

Jump to

Keyboard shortcuts

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