i18n

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 23, 2023 License: MIT Imports: 7 Imported by: 0

README

Simple gin i18n middleware

English | 简体中文

I found that other people's gin i18n middleware too complicated, so I wrote a simple one.

Example

// example/main.go
package main

import (
	"log"
	"net/http"
	"path"

	ginI18n "github.com/fishjar/gin-i18n"
	"github.com/gin-gonic/gin"
)

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

	// apply i18n middleware
	router.Use(ginI18n.Localizer(&ginI18n.Options{
		DefaultLang:  "zh-CN",                          // default language
		SupportLangs: "zh-CN,en-US",                    // list of supported languages ​​(must include default language)
		FilePath:     path.Join("example", "localize"), // multilingual file directory
	}))

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

	router.GET("/:name", func(c *gin.Context) {
		c.String(http.StatusOK, ginI18n.Msg(c, "hello_world", c.Param("name")))
	})

	if err := router.Run(":8080"); err != nil {
		log.Fatal(err)
	}
}
# example/localize/zh-CN.yml
welcome: 欢迎!
hello_world: 你好 %s!
# example/localize/en-US.yml
welcome: welcome!
hello_world: hello %s!
# review
go run example/main.go

curl http://127.0.0.1:8080/ -H 'accept-language: zh-CN'             # 欢迎!
curl http://127.0.0.1:8080/ -H 'accept-language: en-US'             # welcome!

curl http://127.0.0.1:8080/ -H 'accept-language: zh-CN,en-US;q=0.9' # 欢迎!
curl http://127.0.0.1:8080/ -H 'accept-language: zh-CN;q=0.9,en-US' # welcome!

curl http://127.0.0.1:8080/ -H 'accept-language: zh'                # 欢迎!
curl http://127.0.0.1:8080/ -H 'accept-language: en'                # welcome!

curl http://127.0.0.1:8080/gabe -H 'accept-language: zh-CN'         # 你好 gabe!
curl http://127.0.0.1:8080/gabe -H 'accept-language: en-US'         # hello gabe!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Localizer added in v0.0.3

func Localizer(opt *Options) gin.HandlerFunc

Localizer middleware

func Msg added in v0.0.3

func Msg(c *gin.Context, tag string, args ...interface{}) string

Get localizer message

Types

type Options added in v0.0.3

type Options struct {
	DefaultLang  string // default language
	SupportLangs string // list of supported languages ​​(must include default language)
	FilePath     string // multilingual file directory
}

Localizer options

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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