i18n

package module
v2.1.6 Latest Latest
Warning

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

Go to latest
Published: Jun 21, 2024 License: MIT Imports: 11 Imported by: 0

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/charliego3/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.WithLanguageKey("lang"), i18n.WithProvider(i18n.QueryProvider))
   g := i18n.Initialize(
   		i18n.NewLoaderWithPath("./examples/simple"),
     	i18n.WithProvider(i18n.HeaderProvider)
   )
   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(r *http.Request, key string) language.Tag

func FormProvider

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

func HeaderProvider

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

func MustTr

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

MustTr called Tr but ignore error

func ParseFromHeader

func ParseFromHeader(val string) language.Tag

func PostFormProvider

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

func QueryProvider

func QueryProvider(r *http.Request, key string) 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

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

type I18n

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

func Initialize

func Initialize(opts ...Option) *I18n

func (*I18n) Handler

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 LanguageKey

type LanguageKey struct{}

type LanguageProvider

type LanguageProvider[T, U any] func(source T, key U) language.Tag

type Loader

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

type Localized

type Localized = i18n.LocalizeConfig

type Message

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 any) 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 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)))

func WithProvider

func WithProvider[T, U any](provider LanguageProvider[T, U]) 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.WithProvider(i18n.HeaderProvider)
)

type Result

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