Golang网络应用本地化

huangapple go评论89阅读模式
英文:

Golang web app localization

问题

我有一个用Go语言编写的Web应用程序,我计划将其提供给多种语言的用户。我已经查看了多个可用的国际化(l18n)包,但有些问题不太清楚。

哪些包适合确定用户的语言环境并相应地加载网站?比如从浏览器偏好设置或位置信息获取用户的语言环境?

英文:

I have a web app written in golang, and I am planning to make it available in more than one language, I've taken a look at multiple available l18n packages but some things were not clear to me.

What packages would be ideal to determine the users locale and load the site accordingly? Like from browser preferences or location?

答案1

得分: 2

你可以使用https://github.com/nicksnyder/go-i18n/来进行翻译。

然后在你的项目中,你需要创建一个名为i18n/的文件夹,并使用以下函数:

import (
	"fmt"
	"io/ioutil"

	"github.com/nicksnyder/go-i18n/i18n"
)

func loadI18nFiles() {
	files, _ := ioutil.ReadDir("i18n")
	exists := false

	for _, file := range files {
		if err := i18n.LoadTranslationFile(fmt.Sprintf("i18n/%s", file.Name())); err != nil {
			log.Errorf("i18n: error loading file %s. err: %s", file.Name(), err)
		} else {
			log.Infof("i18n: lang file %s loaded", file.Name())
		}

		// 检查是否有默认语言
		if file.Name() == fmt.Sprintf("%s.json", "en-US") {
			exists = true
		}
	}

	if !exists {
		panic(fmt.Sprintf("Hey! You can't use a default language (%s) that doesn't exist in the i18n folder", props.DefaultLang))
	}
}

然后导入该包并调用该函数:

T, _ := i18n.Tfunc("es-AR", "en-US")

fmt.Printf(T("key"))

i18n文件夹中的每个文件都是一个.json文件。

示例:

en-US.json

[
  {
    "id": "key",
    "translation": "Hello World"
  }
]

es-AR.json

[
  {
    "id": "key",
    "translation": "Hola Mundo"
  }
]
英文:

You can use https://github.com/nicksnyder/go-i18n/

Then in your project you have to create a folder called i18n/ and use a function like this:

import (
	"fmt"
	"io/ioutil"

	"github.com/nicksnyder/go-i18n/i18n"
)

func loadI18nFiles() {
	files, _ := ioutil.ReadDir("i18n")
	exists := false

	for _, file := range files {
		if err := i18n.LoadTranslationFile(fmt.Sprintf("i18n/%s", file.Name())); err != nil {
			log.Errorf("i18n: error loading file %s. err: %s", file.Name(), err)
		} else {
			log.Infof("i18n: lang file %s loaded", file.Name())
		}

        # Check if you have a default language
		if file.Name() == fmt.Sprintf("%s.json", "en-US") {
			exists = true
		}
	}

	if !exists {
		panic(fmt.Sprintf("Hey! You can't use a default language (%s) that doesn't exists on i18n folder", props.DefaultLang))
	}
}

Then to use, import the package and call the function:

T, _ := i18n.Tfunc("es-AR", "en-US")

fmt.Printf(T("key"))

Each file inside i18n folder is a .json

Example:

en-US.json

[
  {
    "id": "key",
    "translation": "Hello World"
  }
]

es-AR.json

[
  {
    "id": "key",
    "translation": "Hola Mundo"
  }
]

huangapple
  • 本文由 发表于 2017年8月26日 02:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/45887583.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定