Internationalization

Hertz provides the middleware extension for internationalization (i18n).

Hertz provides the middleware extension for internationalization (i18n), which references Gin’s implementation.

Refer to the below for usage example

Installation

go get github.com/hertz-contrib/i18n

Sample code

package main

import (
    "context"
    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/app/server"
    hertzI18n "github.com/hertz-contrib/i18n"
    "github.com/nicksnyder/go-i18n/v2/i18n"
)

func main() {
    h := server.New(server.WithHostPorts(":3000"))
    h.Use(hertzI18n.Localize())
    h.GET("/:name", func(c context.Context, ctx *app.RequestContext) {
        ctx.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{
            MessageID: "welcomeWithName",
            TemplateData: map[string]string{
             "name": ctx.Param("name"),
          },
         }))
    })
	h.GET("/", func(c context.Context, ctx *app.RequestContext) {
        ctx.String(200, hertzI18n.MustGetMessage(c, "welcome"))
	})

      h.Spin()
}

Configuration

Localize

Localize for integrating the i18n extension into the hertz server

Function Signature:

func Localize(opts ...Option) app.HandlerFunc

Sample code:

package main

import (
    "context"
    _ "embed"
    "time"

    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/app/server"
    hertzI18n "github.com/hertz-contrib/i18n"
    "github.com/nicksnyder/go-i18n/v2/i18n"
    "golang.org/x/text/language"
    "gopkg.in/yaml.v3"
)

func main() {
    h := server.New()
    h.Use(hertzI18n.Localize())
    h.GET("/:name", func(c context.Context, ctx *app.RequestContext) {
        ctx.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{
            MessageID: "welcomeWithName",
            TemplateData: map[string]string{
                "name": ctx.Param("name"),
            },
        }))
    })
    h.GET("/", func(c context.Context, ctx *app.RequestContext) {
        ctx.String(200, hertzI18n.MustGetMessage(c, "welcome"))
    })

    h.Spin()
}

MustGetMessage

MustGetMessage get the i18n message without error handling

Function Signature:

func MustGetMessage(c, param interface{}) string

Sample code:

h.GET("/:name", func(c context.Context, ctx *app.RequestContext) {
	ctx.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{
		MessageID: "welcomeWithName",
		TemplateData: map[string]string{
			"name": ctx.Param("name"),
		},
	}))
})
h.GET("/", func(c context.Context, ctx *app.RequestContext) {
	ctx.String(200, hertzI18n.MustGetMessage(c, "welcome"))
})

LocalizeConfig Configuration item

This configuration item can be viewed by moving to go-i18n

WithBundle

WithBundle is used to load custom configurations into the middleware

Function Signature:

func WithBundle(cfg *BundleCfg) Option

Sample code:

package main

import (
    "context"
    _ "embed"
    "time"

    "github.com/cloudwego/hertz/pkg/app"
    "github.com/cloudwego/hertz/pkg/app/server"
    hertzI18n "github.com/hertz-contrib/i18n"
    "github.com/nicksnyder/go-i18n/v2/i18n"
    "golang.org/x/text/language"
    "gopkg.in/yaml.v3"
)

func main() {
    h := server.New(
        server.WithHostPorts(":3000"),
        server.WithExitWaitTime(time.Second),
    )
    h.Use(hertzI18n.Localize(
        hertzI18n.WithBundle(&hertzI18n.BundleCfg{
            RootPath:         "./localize",
            AcceptLanguage:   []language.Tag{language.Chinese, language.English},
            DefaultLanguage:  language.Chinese,
            FormatBundleFile: "yaml",
            UnmarshalFunc:    yaml.Unmarshal,
        }),
    ))
    h.GET("/:name", func(c context.Context, ctx *app.RequestContext) {
        ctx.String(200, hertzI18n.MustGetMessage(c, &i18n.LocalizeConfig{
            MessageID: "welcomeWithName",
            TemplateData: map[string]string{
                "name": ctx.Param("name"),
            },
        }))
    })
    h.GET("/", func(c context.Context, ctx *app.RequestContext) {
        ctx.String(200, hertzI18n.MustGetMessage(c, "welcome"))
    })

    h.Spin()
}

Configuration item

Configuration items Type Default value Description
DefaultLanguage language.Tag language.English Default conversion language type
FormatBundleFile string “yaml” Convert file template types,For example yaml, json
AcceptLanguage []language.Tag []language.Tag{defaultLanguage,language.Chinese} Receiving conversion type
RootPath string defaultRootPath Template file directory
UnmarshalFunc i18n.UnmarshalFunc yaml.Unmarshal Template file decoding functions,For example: yaml.Unmarshal
Loader Loader LoaderFunc(ioutil.ReadFile) File reading functions, For example : LoaderFunc(ioutil.ReadFile)

WithGetLangHandle

WithGetLangHandle is used to configure the i18n template trigger conditions, which can be retrieved from the parameters, request headers

Function Signature:

func WithGetLangHandle(handler GetLangHandler)

Sample code:

func main() {
    h := server.New()
	h.Use(hertzI18n.Localize(
		hertzI18n.WithGetLangHandle(
			func(c context.Context, ctx *app.RequestContext, defaultLang string) string {
				lang := ctx.Query("lang")
				if lang == "" {
					return defaultLang
				}
				return lang
			},
		),
	))
	// ...
    h.Spin()
}

Refer to the i18n for more usage examples


Last modified January 18, 2024 : Upload volo blog (#936) (1fc8abb)