i18n

package module
v0.0.0-...-34f6598 Latest Latest
Warning

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

Go to latest
Published: Dec 19, 2023 License: MIT Imports: 9 Imported by: 0

README

i18n

Run Tests CodeQL codecov GoDoc Go Report Card

Usage

Download and install it:

go get github.com/gin-contrib/i18n

Import it in your code:

import ginI18n "github.com/gin-contrib/i18n"

Canonical example:

package main

import (
  "log"
  "net/http"

  ginI18n "github.com/gin-contrib/i18n"
  "github.com/gin-gonic/gin"
  "github.com/nicksnyder/go-i18n/v2/i18n"
)

func main() {
  // new gin engine
  gin.SetMode(gin.ReleaseMode)
  router := gin.New()

  // apply i18n middleware
  router.Use(ginI18n.Localize())

  router.GET("/", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, ginI18n.MustGetMessage(ctx, "welcome"))
  })

  router.GET("/:name", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, ginI18n.MustGetMessage(
      ctx,
      &i18n.LocalizeConfig{
        MessageID: "welcomeWithName",
        TemplateData: map[string]string{
          "name": ctx.Param("name"),
        },
      }))
  })

  if err := router.Run(":8080"); err != nil {
    log.Fatal(err)
  }
}

Customized Bundle

package main

import (
  "encoding/json"
  "log"
  "net/http"

  ginI18n "github.com/gin-contrib/i18n"
  "github.com/gin-gonic/gin"
  "github.com/nicksnyder/go-i18n/v2/i18n"
  "golang.org/x/text/language"
)

func main() {
  // new gin engine
  gin.SetMode(gin.ReleaseMode)
  router := gin.New()

  // apply i18n middleware
  router.Use(ginI18n.Localize(ginI18n.WithBundle(&ginI18n.BundleCfg{
    RootPath:         "./testdata/localizeJSON",
    AcceptLanguage:   []language.Tag{language.German, language.English},
    DefaultLanguage:  language.English,
    UnmarshalFunc:    json.Unmarshal,
    FormatBundleFile: "json",
  })))

  router.GET("/", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, ginI18n.MustGetMessage(ctx, "welcome"))
  })

  router.GET("/:name", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, ginI18n.MustGetMessage(
      ctx,
      &i18n.LocalizeConfig{
        MessageID: "welcomeWithName",
        TemplateData: map[string]string{
          "name": ctx.Param("name"),
        },
      }))
  })

  if err := router.Run(":8080"); err != nil {
    log.Fatal(err)
  }
}

Customized Get Language Handler

package main

import (
  "log"
  "net/http"

  ginI18n "github.com/gin-contrib/i18n"
  "github.com/gin-gonic/gin"
  "github.com/nicksnyder/go-i18n/v2/i18n"
)

func main() {
  // new gin engine
  gin.SetMode(gin.ReleaseMode)
  router := gin.New()

  // apply i18n middleware
  router.Use(ginI18n.Localize(
    ginI18n.WithGetLngHandle(
      func(context *gin.Context, defaultLng string) string {
        lng := context.Query("lng")
        if lng == "" {
          return defaultLng
        }
        return lng
      },
    ),
  ))

  router.GET("/", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, ginI18n.MustGetMessage(ctx, "welcome"))
  })

  router.GET("/:name", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, ginI18n.MustGetMessage(
      ctx,
      &i18n.LocalizeConfig{
        MessageID: "welcomeWithName",
        TemplateData: map[string]string{
          "name": ctx.Param("name"),
        },
      }))
  })

  if err := router.Run(":8080"); err != nil {
    log.Fatal(err)
  }
}

License

This project is under MIT License. See the LICENSE file for the full license text.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetMessage

func GetMessage(context *gin.Context, param interface{}) (string, error)

GetMessage get the i18n message with error handling param is one of these type: messageID, *i18n.LocalizeConfig Example: GetMessage(context, "hello") // messageID is hello

GetMessage(context, &i18n.LocalizeConfig{
  MessageID: "welcomeWithName",
  TemplateData: map[string]string{
    "name": context.Param("name"),
  },
})

func Localize

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

Localize ...

func MustGetMessage

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

MustGetMessage get the i18n message without error handling param is one of these type: messageID, *i18n.LocalizeConfig Example: MustGetMessage(context, "hello") // messageID is hello

MustGetMessage(context, &i18n.LocalizeConfig{
  MessageID: "welcomeWithName",
  TemplateData: map[string]string{
    "name": context.Param("name"),
  },
})

Types

type BundleCfg

type BundleCfg struct {
	DefaultLanguage  language.Tag
	FormatBundleFile string
	AcceptLanguage   []language.Tag
	RootPath         string
	UnmarshalFunc    i18n.UnmarshalFunc
	Loader           Loader
}

BundleCfg ...

type EmbedLoader

type EmbedLoader struct {
	FS embed.FS
}

func (*EmbedLoader) LoadMessage

func (c *EmbedLoader) LoadMessage(path string) ([]byte, error)

type GetLngHandler

type GetLngHandler = func(context *gin.Context, defaultLng string) string

GetLngHandler ...

type GinI18n

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

GinI18n ...

type Loader

type Loader interface {
	LoadMessage(path string) ([]byte, error)
}

type LoaderFunc

type LoaderFunc func(path string) ([]byte, error)

func (LoaderFunc) LoadMessage

func (f LoaderFunc) LoadMessage(path string) ([]byte, error)

type Option

type Option func(GinI18n)

Option ...

func WithBundle

func WithBundle(config *BundleCfg) Option

WithBundle ...

func WithGetLngHandle

func WithGetLngHandle(handler GetLngHandler) Option

WithGetLngHandle ...

Jump to

Keyboard shortcuts

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