i18n

package module
v2.1.3 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2022 License: MIT Imports: 11 Imported by: 1

README

go-i18n

GitHub Workflow Status (branch) Go Report Card Coveralls GitHub tag (latest SemVer pre-release) GitHub GoDoc

Provides simplicity and ease of use, no specific framework restrictions, easy access to any framework based on http.Handler

Table of Contents

Installation

go get github.com/Charliego93/go-i18n

Usage

package main

import (
   "embed"
   "fmt"
   "github.com/Charliego93/go-i18n/v2"
   "github.com/gin-gonic/gin"
   "golang.org/x/text/language"
   "net/http"
)

//go:embed examples/lan2/*
var langFS embed.FS

func main() {
   engine := gin.New()

   // curl -H "Accept-Language: en" 'http://127.0.0.1:9090/Hello'  returns "hello"
   // curl -H "Accept-Language: uk" 'http://127.0.0.1:9090/Hello'  returns "Бонгу"
   // curl 'http://127.0.0.1:9090/Hello?lang=en'  returns "hello"
   // curl 'http://127.0.0.1:9090/Hello?lang=uk'  returns "Бонгу"
   engine.GET("/:messageId", func(ctx *gin.Context) {
      ctx.String(http.StatusOK, i18n.MustTr(ctx.Request.Context(), ctx.Param("messageId")))
   })

   // curl -H "Accept-Language: en" 'http://127.0.0.1:9090/HelloName/I18n'  returns "hello I18n"
   // curl -H "Accept-Language: uk" 'http://127.0.0.1:9090/HelloName/I18n'  returns "Бонгу I18n"
   // curl 'http://127.0.0.1:9090/HelloName/I18n?lang=en'  returns "hello I18n"
   // curl 'http://127.0.0.1:9090/HelloName/I18n?lang=uk'  returns "Бонгу I18n"
   engine.GET("/:messageId/:name", func(ctx *gin.Context) {
      ctx.String(http.StatusOK, i18n.MustTr(ctx.Request.Context(), &i18n.LocalizeConfig{
         MessageID: ctx.Param("messageId"),
         TemplateData: map[string]string{
            "Name": ctx.Param("name"),
         },
      }))
   })

   // Use multi loader provider
   // Built-in load from file and load from fs.FS
   // i18n.Initialize(i18n.NewLoaderWithFS(langFS), i18n.NewLoaderWithPath("./examples/lan1"))))
   g := i18n.Initialize(i18n.NewLoaderWithPath("./examples/simple"))
   if err := http.ListenAndServe(":9090", g.Handler(engine)); err != nil {
      panic(err)
   }
}

Customize Loader

You can implement your own Loader by yourself, and even pull the language files from anywhere

type Loader interface {
    Load() (*Result, error)
}

type Result struct {
   Funcs   map[string]UnmarshalFunc
   Entries []Entry
}

type Entry struct {
   Lauguage language.Tag
   Name     string
   Bytes    []byte
}

License

MIT © Charliego93.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CookieProvider

func CookieProvider(key string, r *http.Request) language.Tag

func FormProvider

func FormProvider(key string, r *http.Request) language.Tag

func HeaderProvider

func HeaderProvider(_ string, r *http.Request) language.Tag

func MustTr

func MustTr[T Message](ctx context.Context, message T) string

MustTr called Tr but ignore error

func ParseFromHeader added in v2.1.1

func ParseFromHeader(val string) language.Tag

func PostFormProvider

func PostFormProvider(key string, r *http.Request) language.Tag

func QueryProvider

func QueryProvider(key string, r *http.Request) language.Tag

func Tr

func Tr[T Message](ctx context.Context, message T) (string, error)

Tr translate messageId to target language

Example:

Tr(ctx, "hello")
Tr(ctx, &Localized{
	Message: "HelloName",
	TemplateData: map[string]string{
		"Name": "I18n",
	},
})

Types

type Entry added in v2.1.0

type Entry struct {
	Tag   language.Tag
	Name  string
	Bytes []byte
}

type I18n added in v2.1.0

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

func Initialize added in v2.1.0

func Initialize(opts ...Option) *I18n

func (*I18n) Handler added in v2.1.0

func (g *I18n) Handler(next http.Handler) http.Handler

Handler returns http.Handler. It can be using a middleware...

type LOpt

type LOpt func(*fsLoader)

func WithUnmarshal

func WithUnmarshal(format string, fn UnmarshalFunc) LOpt

WithUnmarshal register single format unmarshal func

func WithUnmarshalls

func WithUnmarshalls(fns map[string]UnmarshalFunc) LOpt

WithUnmarshalls register multi format unmarshal func

type LanguageProvider

type LanguageProvider func(string, *http.Request) language.Tag

type Loader

type Loader interface {
	Load() (*Result, error)
}

type Localized added in v2.1.3

type Localized = i18n.LocalizeConfig

type Message added in v2.1.3

type Message interface {
	~string | Localized | ~*Localized
}

type Option

type Option func(*I18n)

func NewLoaderWithFS

func NewLoaderWithFS(fs fs.FS, opts ...LOpt) Option

func NewLoaderWithPath

func NewLoaderWithPath(path string, opts ...LOpt) Option

func WithDefaultLanguage

func WithDefaultLanguage(tag language.Tag) Option

WithDefaultLanguage specify the default language, which is used when it is not available from the LanguageProvider

Example:

i18n.loader :=i18n.NewLoaderWithPath("language_file_path")
i18n.Handler(http.Handler, i18n.WithLoader(loader), i18n.WithDefaultLanguage(language.Chinese))

func WithLanguageKey

func WithLanguageKey(key string) Option

WithLanguageKey specifies the default language key when obtained from the LanguageProvider Except from the Header, there is no limit if you specify LanguageProvider manually

Example:

i18n.loader :=i18n.NewLoaderWithPath("language_file_path")
i18n.Handler(http.Handler, i18n.WithLoader(loader), i18n.WithLanguageKey("default_language_key"))

func WithLanguageProvider

func WithLanguageProvider(providers ...LanguageProvider) Option

WithLanguageProvider get the language from *http.Request, default LanguageProvider the order of acquisition is: header(always get the value of Accept-Language) -> cookie -> query -> form -> postForm you can use WithLanguageKey change the default lang key

Example:

loader := i18n.NewLoaderWithPath("language_file_path")
i18n.Handler(http.Handler, i18n.WithLoader(loader),
    i18n.WithLanguageProvider(i18n.LangHandlerFunc(func(r *http.Request) language.Tag {
	    lang := r.Header.Get("Accept-Language")
	    tag, err := language.Parse(lang)
	    if err != nil {
		    return language.Chinese
	    }
	    return tag
    },
)))

func WithLoader

func WithLoader(loader Loader) Option

WithLoader Register the Loader interface to *I18n.bundle

Example:

//go:embed examples/lan2/*
var langFS embed.FS
i18n.Handler(http.Handler, i18n.NewLoaderWithPath("language_file_path"))
i18n.Handler(http.Handler, i18n.NewLoaderWithFS(langFS, i18n.WithUnmarshal("json", json.Unmarshal)))

type Result added in v2.1.0

type Result struct {
	Funcs   map[string]UnmarshalFunc
	Entries []Entry
}

type UnmarshalFunc

type UnmarshalFunc = i18n.UnmarshalFunc

Jump to

Keyboard shortcuts

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