Provides simplicity and ease of use, no specific framework restrictions, easy access to any framework based on http.Handler
go get github.com/Charliego93/go-i18n
package main
import (
"embed"
"fmt"
"github.com/charliego3/go-i18n/v2"
"github.com/gin-gonic/gin"
"golang.org/x/text/language"
"net/http"
)
//go:embed examples/lan2/*
var langFS embed.FS
func main() {
engine := gin.New()
// curl -H "Accept-Language: en" 'http://127.0.0.1:9090/Hello' returns "hello"
// curl -H "Accept-Language: uk" 'http://127.0.0.1:9090/Hello' returns "Бонгу"
// curl 'http://127.0.0.1:9090/Hello?lang=en' returns "hello"
// curl 'http://127.0.0.1:9090/Hello?lang=uk' returns "Бонгу"
engine.GET("/:messageId", func(ctx *gin.Context) {
ctx.String(http.StatusOK, i18n.MustTr(ctx.Request.Context(), ctx.Param("messageId")))
})
// curl -H "Accept-Language: en" 'http://127.0.0.1:9090/HelloName/I18n' returns "hello I18n"
// curl -H "Accept-Language: uk" 'http://127.0.0.1:9090/HelloName/I18n' returns "Бонгу I18n"
// curl 'http://127.0.0.1:9090/HelloName/I18n?lang=en' returns "hello I18n"
// curl 'http://127.0.0.1:9090/HelloName/I18n?lang=uk' returns "Бонгу I18n"
engine.GET("/:messageId/:name", func(ctx *gin.Context) {
ctx.String(http.StatusOK, i18n.MustTr(ctx.Request.Context(), &i18n.LocalizeConfig{
MessageID: ctx.Param("messageId"),
TemplateData: map[string]string{
"Name": ctx.Param("name"),
},
}))
})
// Use multi loader provider
// Built-in load from file and load from fs.FS
// i18n.Initialize(i18n.NewLoaderWithFS(langFS), i18n.WithLanguageKey("lang"), i18n.WithProvider(i18n.QueryProvider))
g := i18n.Initialize(
i18n.NewLoaderWithPath("./examples/simple"),
i18n.WithProvider(i18n.HeaderProvider)
)
if err := http.ListenAndServe(":9090", g.Handler(engine)); err != nil {
panic(err)
}
}
You can implement your own Loader
by yourself, and even pull the language files from anywhere
type Loader interface {
Load() (*Result, error)
}
type Result struct {
Funcs map[string]UnmarshalFunc
Entries []Entry
}
type Entry struct {
Lauguage language.Tag
Name string
Bytes []byte
}