i18n

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2024 License: MIT Imports: 6 Imported by: 0

README

i18n

i18n is a simple internationalization library for Golang. It provides a way to translate strings into multiple languages. This library is wrapper for go-i18n with some additional features.

Installation

go get -u github.com/ahmadfaizk/i18n

Features

  • Translation
  • Context Translation
  • Parametrized Translation
  • Missing Translation Fallback

Usage

Create Translation File
# locale/en.yaml
hello: Hello
hello_name: Hello, %s
# locale/id.yaml
hello: Halo
hello_name: Halo, %s
Basic
package main

import (
	"fmt"
	"github.com/ahmadfaizk/i18n"
	"golang.org/x/text/language"
)

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

	fmt.Println(i18n.T("hello")) // Hello
	fmt.Println(i18n.T("hello", i18n.Lang("id"))) // Halo
	fmt.Println(i18n.T("hello_name", i18n.Param("name", "John"))) // Hello, John
	fmt.Println(i18n.T("hello_name", i18n.Lang("id"), i18n.Param("name", "John"))) // Halo, John
}
Using Context (e.g. with chi router)
package main

import (
	"fmt"
	"github.com/ahmadfaizk/i18n"
	"github.com/go-chi/chi"
	"golang.org/x/text/language"
	"net/http"
)

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

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

	if err := http.ListenAndServe(":8080", r); err != nil {
        panic(err)
    }
}

License

This project is licensed under the MIT License - see the 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

View Source
var (
	ErrI18nNotInitialized = errors.New("i18n is not initialized")
)

Functions

func Get

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

Get returns the translated message for the given message id.

It uses the default language tag.

Example:

message := i18n.Get("hello", i18n.Param("name", "John"))

func GetCtx

func GetCtx(ctx context.Context, id string, opts ...LocalizeOption) 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.Param("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("localization/en.yaml", "localization/id.yaml"),
) err != nil {
	panic(err)
}

func Middleware

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

Middleware is a middleware that sets the language to the context from the request.

It uses the Accept-Language header to get the language. But you can also customize with WithLanguageExtractFunc option.

func SetLanguageToContext

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

SetLanguageToContext sets the language to the context.

func T

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

T is an alias for Get.

Example:

message := i18n.T("hello", i18n.Param("name", "John"))

func TCtx

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

TCtx is an alias for GetCtx.

Example:

message := i18n.TCtx(ctx, "hello", i18n.Param("name", "John"))

Types

type LocalizeOption

type LocalizeOption func(*localizeConfig)

LocalizeOption is a function that configures the localizeConfig.

func DefaultMessage

func DefaultMessage(defaultMessage string) LocalizeOption

DefaultMessage sets the default message for the message.

It is used when the message is not found.

Example:

i18n.T("hello", i18n.DefaultMessage("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 interface{}) LocalizeOption

Param sets template data for the message.

Example:

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

func Params

func Params(params map[string]interface{}) LocalizeOption

Params sets template data for the message.

Example:

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

type Map

type Map map[string]interface{}

Map is a map of string to interface. It is used to pass template data to the message.

type MiddlewareOption

type MiddlewareOption func(*middlewareConfig)

MiddlewareOption is the option for the middleware.

func WithLanguageExtractFunc

func WithLanguageExtractFunc(languageExtractFunc func(*http.Request) string) MiddlewareOption

WithLanguageExtractFunc sets the language from the request.

Example:

i18n.Middleware(i18n.WithLanguageExtractFunc(func(r *http.Request) string {
	lang := r.Header.Get("Accept-Language")
	if lang == "" {
		lang = r.URL.Query().Get("lang")
	}
	return lang
}))

type Option

type Option func(*config)

Option is the option for the i18n package.

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.

Jump to

Keyboard shortcuts

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