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

    h.Spin()
}

MustGetMessage

MustGetMessage get the i18n message without error handling

Function Signature:

func MustGetMessage(ctx context.Context, param interface{}) string

Sample code:

h.GET("/:name", func(ctx context.Context, c *app.RequestContext) {
	c.String(200, hertzI18n.MustGetMessage(ctx, &i18n.LocalizeConfig{
		MessageID: "welcomeWithName",
		TemplateData: map[string]string{
			"name": c.Param("name"),
		},
	}))
})
h.GET("/", func(ctx context.Context, c *app.RequestContext) {
	c.String(200, hertzI18n.MustGetMessage(ctx, "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(ctx context.Context, c *app.RequestContext) {
        c.String(200, hertzI18n.MustGetMessage(ctx, &i18n.LocalizeConfig{
            MessageID: "welcomeWithName",
            TemplateData: map[string]string{
                "name": c.Param("name"),
            },
        }))
    })
    h.GET("/", func(ctx context.Context, c *app.RequestContext) {
        c.String(200, hertzI18n.MustGetMessage(ctx, "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(ctx context.Context, c *app.RequestContext, defaultLang string) string {
				lang := c.Query("lang")
				if lang == "" {
					return defaultLang
				}
				return lang
			},
		),
	))
	// ...
    h.Spin()
}

Refer to the i18n for more usage examples


Last modified November 11, 2024 : chore: update project descriptions (#1166) (1716eba)