i18n

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Mar 9, 2022 License: MIT Imports: 12 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"
   "github.com/gin-gonic/gin"
   "net/http"
)

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

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

   // returns the default language if the header and language key are not specified or if the language does not exist
   engine.Use(gin.WrapH(i18n.Localize(language.Chinese, i18n.NewLoaderWithPath("./examples/simple"))))

   // Use multi loader provider
   // Built-in load from file and load from fs.FS
   // engine.Use(gin.WrapH(i18n.Localize(language.Chinese, 
   //    i18n.NewLoaderWithFS(langFS), i18n.NewLoaderWithPath("./examples/lan1"))))

   // 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.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(&i18n.LocalizeConfig{
         MessageID: ctx.Param("messageId"),
         TemplateData: map[string]string{
            "Name": ctx.Param("name"),
         },
      }))
   })

   fmt.Println(engine.Run())
}

Customize Loader

You can implement your own Loader by yourself, and even pull the language files from any possible place to use, just pay attention when implementing the ParseMessage(i *I18n) error function:

  1. At least need to call i.SetLocalizer(language.Tag) and i.MastParseMessageFileBytes([]byte, string) to register with Bundle
    • []byte is the file content
    • string is the file path: mainly used to parse the language and serialization type, for example: en.yaml
  2. Sometimes it is necessary to call i.RegisterUnmarshalFunc(string, UnmarshalFunc) to register the deserialization function:
    • string is the format type. eg: yaml
    • UnmarshalFunc eg: json.Unmarshal or yaml.Unmarshal

License

MIT © Charliego93.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MustTr

func MustTr(messageId interface{}) string

MustTr called Tr but ignore error

func Tr

func Tr(messageId interface{}) (string, error)

Tr translate messageId to target language

Example:

Tr("hello")
Tr(LocalizeConfig{
	MessageID: "HelloName",
	TemplateData: map[string]string{
		"Name": "I18n",
	},
})

Types

type ContextHandler

type ContextHandler struct{}

func Localize

func Localize(defaultLang language.Tag, opts ...Option) ContextHandler

Localize initialize i18n...

func (ContextHandler) ServeHTTP

func (_ ContextHandler) ServeHTTP(_ http.ResponseWriter, r *http.Request)

type FSLoader

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

func (*FSLoader) ParseMessage

func (c *FSLoader) ParseMessage(i *I18n) error

type I18n

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

func (*I18n) AddLoader

func (i *I18n) AddLoader(loader Loader)

func (*I18n) MastParseMessageFileBytes

func (i *I18n) MastParseMessageFileBytes(buf []byte, path string)

func (*I18n) RegisterUnmarshalFunc

func (i *I18n) RegisterUnmarshalFunc(format string, unmarshalFunc UnmarshalFunc)

func (*I18n) SetDefaultLang

func (i *I18n) SetDefaultLang(lang language.Tag)

func (*I18n) SetLocalizer

func (i *I18n) SetLocalizer(lang language.Tag)

func (*I18n) Tr

func (i *I18n) Tr(p interface{}) (string, error)

type LangHandler

type LangHandler interface {
	Language(*http.Request) language.Tag
}

type LangHandlerFunc

type LangHandlerFunc func(*http.Request) language.Tag

func (LangHandlerFunc) Language

func (f LangHandlerFunc) Language(r *http.Request) language.Tag

type Loader

type Loader interface{ ParseMessage(i *I18n) error }

type LoaderOp

type LoaderOp interface {
	// contains filtered or unexported methods
}

func WithUnmarshal

func WithUnmarshal(format string, fn UnmarshalFunc) LoaderOp

WithUnmarshal register single format unmarshal func

func WithUnmarshalls

func WithUnmarshalls(fns map[string]UnmarshalFunc) LoaderOp

WithUnmarshalls register multi format unmarshal func

type LoaderOpFunc

type LoaderOpFunc func(cfg *FSLoader)

type LocalizeConfig

type LocalizeConfig = i18n.LocalizeConfig

type Option

type Option interface {
	// contains filtered or unexported methods
}

func NewLoaderWithFS

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

func NewLoaderWithPath

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

func WithLangHandler

func WithLangHandler(handler LangHandler) Option

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

Example:

loader := i18n.NewLoaderWithPath("language_file_path")
i18n.Localize(language.Chinese, loader, i18n.WithLangHandler(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 WithLangKey

func WithLangKey(key string) Option

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

Example:

i18n.loader :=i18n.NewLoaderWithPath("language_file_path")
i18n.Localize(language.Chinese, loader, i18n.WithLangKey("default_language_key"))

func WithLoader

func WithLoader(l Loader) Option

WithLoader Register the Loader interface to *I18n.bundle

Example:

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

type OptionFunc

type OptionFunc func(*I18n)

type UnmarshalFunc

type UnmarshalFunc = i18n.UnmarshalFunc

Jump to

Keyboard shortcuts

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