i18n

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2024 License: MIT Imports: 9 Imported by: 32

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("/messageId/:name", func(context *gin.Context) {
    context.String(http.StatusOK, MustGetMessage(context, &i18n.LocalizeConfig{
      MessageID: "welcomeWithName",
      TemplateData: map[string]string{
        "name": context.Param("name"),
      },
    }))
  })

  router.GET("/messageType/:name", func(context *gin.Context) {
    context.String(http.StatusOK, MustGetMessage(context, &i18n.LocalizeConfig{
      DefaultMessage: &i18n.Message{
        ID: "welcomeWithName",
      },
      TemplateData: map[string]string{
        "name": context.Param("name"),
      },
    }))
  })
  
  router.GET("/exist/:lang", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, "%v", ginI18n.HasLang(ctx, ctx.Param("lang")))
  })

  // get the default and current language
  router.GET("/lang/default", func(context *gin.Context) {
    context.String(http.StatusOK, "%s", GetDefaultLanguage(context).String())
  })

  // get the current language
  router.GET("/lang/current", func(context *gin.Context) {
    context.String(http.StatusOK, "%s", GetCurrentLanguage(context).String())
  })

  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("/messageId/:name", func(context *gin.Context) {
    context.String(http.StatusOK, MustGetMessage(context, &i18n.LocalizeConfig{
      MessageID: "welcomeWithName",
      TemplateData: map[string]string{
        "name": context.Param("name"),
      },
    }))
  })

  router.GET("/messageType/:name", func(context *gin.Context) {
    context.String(http.StatusOK, MustGetMessage(context, &i18n.LocalizeConfig{
      DefaultMessage: &i18n.Message{
        ID: "welcomeWithName",
      },
      TemplateData: map[string]string{
        "name": context.Param("name"),
      },
    }))
  })

  router.GET("/exist/:lang", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, "%v", ginI18n.HasLang(ctx, ctx.Param("lang")))
  })

  // get the default and current language
  router.GET("/lang/default", func(context *gin.Context) {
    context.String(http.StatusOK, "%s", GetDefaultLanguage(context).String())
  })

  // get the current language
  router.GET("/lang/current", func(context *gin.Context) {
    context.String(http.StatusOK, "%s", GetCurrentLanguage(context).String())
  })

  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("/messageId/:name", func(context *gin.Context) {
    context.String(http.StatusOK, MustGetMessage(context, &i18n.LocalizeConfig{
      MessageID: "welcomeWithName",
      TemplateData: map[string]string{
        "name": context.Param("name"),
      },
    }))
  })

  router.GET("/messageType/:name", func(context *gin.Context) {
    context.String(http.StatusOK, MustGetMessage(context, &i18n.LocalizeConfig{
      DefaultMessage: &i18n.Message{
        ID: "welcomeWithName",
      },
      TemplateData: map[string]string{
        "name": context.Param("name"),
      },
    }))
  })

  router.GET("/exist/:lang", func(ctx *gin.Context) {
    ctx.String(http.StatusOK, "%v", ginI18n.HasLang(ctx, ctx.Param("lang")))
  })

  // get the default and current language
  router.GET("/lang/default", func(context *gin.Context) {
    context.String(http.StatusOK, "%s", GetDefaultLanguage(context).String())
  })

  // get the current language
  router.GET("/lang/current", func(context *gin.Context) {
    context.String(http.StatusOK, "%s", GetCurrentLanguage(context).String())
  })

  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

Overview

Package i18n ginI18nImpl is an implementation of the GinI18n interface, providing localization support for Gin applications. It uses the go-i18n library to manage and retrieve localized messages.

Fields: - bundle: The i18n.Bundle containing the localization messages. - localizerByLng: A map of language tags to their corresponding localizers. - defaultLanguage: The default language tag to use for localization. - getLngHandler: A handler function to retrieve the language tag from the Gin context.

Methods: - GetMessage: Retrieves a localized message based on the provided context and parameter. - MustGetMessage: Retrieves a localized message and returns an empty string if retrieval fails. - HasLang: Checks if a specific language is supported. - GetCurrentLanguage: Retrieves the current language based on the Gin context.. - GetDefaultLanguage: Retrieves the default language - SetBundle: Sets the i18n.Bundle configuration. - SetGetLngHandler: Sets the handler function to retrieve the language tag from the Gin context. - loadMessageFiles: Loads all localization files into the bundle. - loadMessageFile: Loads a single localization file into the bundle. - setLocalizerByLng: Sets the localizers for each accepted language. - newLocalizer: Creates a new localizer for a given language. - getLocalizerByLng: Retrieves the localizer for a given language. - getLocalizeConfig: Converts the parameter into an i18n.LocalizeConfig.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetCurrentLanguage added in v1.2.0

func GetCurrentLanguage(context *gin.Context) language.Tag

GetCurrentLanguage get the current language Example: GetCurrentLanguage(context)

func GetDefaultLanguage added in v1.2.0

func GetDefaultLanguage(context *gin.Context) language.Tag

GetDefaultLanguage get the default language Example: GetDefaultLanguage(context)

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 HasLang added in v1.2.0

func HasLang(context *gin.Context, language string) bool

HasLang check all i18n lang exists Example: HasLang(context, "ZH-cn") // return false or true

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       // DefaultLanguage specifies the default language for the bundle.
	FormatBundleFile string             // FormatBundleFile specifies the file format for the bundle.
	AcceptLanguage   []language.Tag     // AcceptLanguage specifies the accepted languages for the bundle.
	RootPath         string             // RootPath specifies the root path for the bundle.
	UnmarshalFunc    i18n.UnmarshalFunc // UnmarshalFunc specifies the function used for unmarshaling bundle files.
	Loader           Loader             // Loader specifies the loader for loading bundle files.
}

BundleCfg represents the configuration options for an i18n bundle.

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

Option is a function type that takes a GinI18n instance and applies a configuration to it. It is used to customize the behavior of the GinI18n middleware.

type GinI18n

type GinI18n interface {
	// GetMessage retrieves a localized message based on the provided context and parameter.
	// It returns the localized message as a string and an error if the message could not be retrieved.
	GetMessage(context *gin.Context, param interface{}) (string, error)

	// MustGetMessage retrieves a localized message based on the provided context and parameter.
	// It returns the localized message as a string and panics if the message could not be retrieved.
	MustGetMessage(context *gin.Context, param interface{}) string

	// SetBundle sets the i18n bundle configuration.
	SetBundle(cfg *BundleCfg)

	// SetGetLngHandler sets the handler function to determine the language from the context.
	SetGetLngHandler(handler GetLngHandler)

	// HasLang checks if the given language is supported by the i18n bundle.
	// It returns true if the language is supported, false otherwise.
	HasLang(language string) bool

	// GetDefaultLanguage returns the default language tag.
	// It returns the default language tag.
	GetDefaultLanguage() language.Tag

	// GetCurrentLanguage returns the current language tag from the context.
	// It returns the current language tag.
	GetCurrentLanguage(context *gin.Context) language.Tag
}

GinI18n is an interface that defines methods for internationalization (i18n) in a Gin web framework context. It provides methods to get localized messages and configure the i18n bundle and language handler.

func I18n added in v1.2.0

func I18n(context *gin.Context) GinI18n

I18n get GinI18n from gin.Context

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 is a function type that takes a GinI18n instance and applies a configuration to it.

func WithBundle

func WithBundle(config *BundleCfg) Option

WithBundle returns an Option that sets the bundle configuration for GinI18n. If the loader is not provided in the BundleCfg, the defaultLoader will be used.

func WithGetLngHandle

func WithGetLngHandle(handler GetLngHandler) Option

WithGetLngHandle sets the handler function for retrieving the current language. The provided handler function should accept a GinI18n instance and return the current language as a string. This option allows you to customize how the current language is determined.

Jump to

Keyboard shortcuts

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