Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >go-i18n 国际化工具使用样例

go-i18n 国际化工具使用样例

原创
作者头像
软件书桌
发布于 2024-05-30 09:43:07
发布于 2024-05-30 09:43:07
1K01
代码可运行
举报
运行总次数:1
代码可运行

i18n(国际化)

国际化称作 i18n,其来源是英文单词 internationalization 的首末字符 i 和 n,18 为中间的字符数。由于软件发行可能面向多个国家,对于不同国家的用户,软件显示不同语言的过程就是国际化。通常来讲,软件中的国际化是通过配置文件来实现的,假设要支撑两种语言,那么就需要两个版本的配置文件。

现在大部分的应用基本都是前后端分离架构,但是只要有需要后端渲染的功能,则后端依然会存在国际化的场景。

例如:下载 Excel,导出 PDF,发送邮件通知等。

这些场景中的通用语言可以使用 i18n 国际化的方式进行开发维护。

国际化的标准做法是每种语言模式定义一个通用语言的模板文件。

业务代码根据当前上下文中的语言模式,从对应的语言模版中提取通用语言对应的语种的表达。

在 Go 技术栈中,可以使用 /nicksnyder/go-i18n 这个框架,这个框架比较热门。

GitHub - nicksnyder/go-i18n: Translate your Go program into multiple languages.

https://github.com/nicksnyder/go-i18n

官方案例的调试

官方提供的例子中默认语种的数据是在代码里直接初始化的,实际上我们会将各个语种的数据都放在模版文件中。

以下就是基于官方 example 修改的一个这样的例子。

  • main.go

MessageID 这个属性很重要,通过这个属性定位到使用 toml 中哪个数据。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// Command example runs a sample webserver that uses go-i18n/v2/i18n.
package main

import (
   "fmt"
   "html/template"
   "log"
   "net/http"
   "strconv"

   "github.com/BurntSushi/toml"
   "github.com/nicksnyder/go-i18n/v2/i18n"
   "golang.org/x/text/language"
)

var page = template.Must(template.New("").Parse(`
<!DOCTYPE html>
<html>
<body>

<h1>{{.Title}}</h1>

{{range .Paragraphs}}<p>{{.}}</p>{{end}}

</body>
</html>
`))

func main() {

   bundle := i18n.NewBundle(language.English)
   bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)
   // No need to load active.en.toml since we are providing default translations.
   // bundle.MustLoadMessageFile("active.en.toml")
   bundle.MustLoadMessageFile("./example/active.es.toml")
   bundle.MustLoadMessageFile("./example/active.en.toml")

   http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
      lang := r.FormValue("lang")
      if lang == "" {
         lang = "en"
      }
      localizer := i18n.NewLocalizer(bundle, lang)

      name := r.FormValue("name")
      if name == "" {
         name = "Bob"
      }

      unreadEmailCount, _ := strconv.ParseInt(r.FormValue("unreadEmailCount"), 10, 64)

      helloPerson := localizer.MustLocalize(&i18n.LocalizeConfig{
         DefaultMessage: &i18n.Message{
            ID:    "HelloPerson",
            Other: "Hello {{.Name}}",
         },
         TemplateData: map[string]string{
            "Name": name,
         },
      })

      myUnreadEmails := localizer.MustLocalize(&i18n.LocalizeConfig{
         MessageID:   "MyUnreadEmails",
         PluralCount: unreadEmailCount,
      })

      personUnreadEmails := localizer.MustLocalize(&i18n.LocalizeConfig{
         MessageID:   "PersonUnreadEmails",
         PluralCount: unreadEmailCount,
         TemplateData: map[string]interface{}{
            "Name":             name,
            "UnreadEmailCount": unreadEmailCount,
         },
      })

      err := page.Execute(w, map[string]interface{}{
         "Title": helloPerson,
         "Paragraphs": []string{
            myUnreadEmails,
            personUnreadEmails,
         },
      })
      if err != nil {
         panic(err)
      }
   })

   fmt.Println("Listening on http://localhost:8080")
   log.Fatal(http.ListenAndServe(":8080", nil))
}
  • active.es.toml
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[HelloPerson]
hash = "sha1-5b49bfdad81fedaeefb224b0ffc2acc58b09cff5"
other = "Hola {{.Name}}"

[MyUnreadEmails]
description = "The number of unread emails I have"
hash = "sha1-6a65d17f53981a3657db1897630e9cb069053ea8"
one = "Tengo {{.PluralCount}} correo electrónico sin leer"
other = "Tengo {{.PluralCount}} correos electrónicos no leídos"

[PersonUnreadEmails]
description = "The number of unread emails a person has"
hash = "sha1-3a672fa89c5c8564bb233c907638004983792464"
one = "{{.Name}} tiene {{.UnreadEmailCount}} correo electrónico no leído"
other = "{{.Name}} tiene {{.UnreadEmailCount}} correos electrónicos no leídos"
  • active.en.toml
代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
HelloPerson = "Hello {{.Name}}"

[MyUnreadEmails]
description = "The number of unread emails I have"
one = "I have {{.PluralCount}} unread email."
other = "I have {{.PluralCount}} unread emails."

[PersonUnreadEmails]
description = "The number of unread emails a person has"
one = "{{.Name}} has {{.UnreadEmailCount}} unread email."
other = "{{.Name}} has {{.UnreadEmailCount}} unread emails."

Then open http://localhost:8080 in your web browser.

You can customize the template data and locale via query parameters like this: http://localhost:8080/?name=Nick&unreadEmailCount=2 http://localhost:8080/?name=Nick&unreadEmailCount=2&lang=es

微服务中使用示例

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import (
   "github.com/nicksnyder/go-i18n/v2/i18n"
   "golang.org/x/text/language"
)

func i18nExample() {
   bundle := i18n.NewBundle(language.English)
   bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal)

   bundle.MustLoadMessageFile("./lang/active.zh.toml")
   bundle.MustLoadMessageFile("./lang/active.en.toml")

   localizer := i18n.NewLocalizer(bundle, "zh")

   languageMode := localizer.MustLocalize(&i18n.LocalizeConfig{
      MessageID: "LanguageMode",
   })

   fmt.Println(languageMode)

}

go.mod

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
module platform

go 1.18

require (
   github.com/DATA-DOG/go-sqlmock v1.5.0
   github.com/agiledragon/gomonkey/v2 v2.4.0
   github.com/fatih/structs v1.1.0
   github.com/fsnotify/fsnotify v1.4.9
   github.com/gin-gonic/gin v1.7.7
   github.com/golang/mock v1.5.0
   github.com/google/uuid v1.3.0
   github.com/hashicorp/go-retryablehttp v0.7.1
   github.com/iancoleman/strcase v0.2.0
   github.com/imroc/req v0.3.2
   github.com/jinzhu/copier v0.3.4
   github.com/json-iterator/go v1.1.12
   github.com/nicksnyder/go-i18n/v2 v2.4.0
   github.com/pelletier/go-toml v1.9.3
   github.com/pkg/errors v0.9.1
   github.com/sirupsen/logrus v1.8.1
   github.com/spf13/pflag v1.0.5
   github.com/spf13/viper v1.8.0
   github.com/stretchr/testify v1.7.0
   github.com/toolkits/net v0.0.0-20160910085801-3f39ab6fe3ce
   gitlab.archeros.cn/Haihe/go-core v1.6.1
   gitlab.archeros.cn/Haihe/haihe-sdk-go v1.7.1-0.20230821085944-1943b464f7d3
   go.etcd.io/etcd/client/v3 v3.5.1
   go.uber.org/automaxprocs v1.4.0
   golang.org/x/sys v0.5.0
   golang.org/x/text v0.15.0
   gopkg.in/go-playground/validator.v9 v9.31.0
   gorm.io/driver/mysql v1.3.2
   gorm.io/gorm v1.23.1
)

active.zh.toml

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[LanguageMode]
description = "语言模式"
other = "中文模式"

active.en.toml

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
[LanguageMode]
description = "语言模式"
other = "EnglishMode"

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
知识分享之Golang——go-i18n国际化组件
知识分享之Golang篇是我在日常使用Golang时学习到的各种各样的知识的记录,将其整理出来以文章的形式分享给大家,来进行共同学习。欢迎大家进行持续关注。
cn華少
2021/11/29
2.7K0
基于 Go 语言开发在线论坛(八):消息、视图及日期时间本地化
我们接着上篇在线论坛的进度,由于之前所有页面和消息文本都是英文的,而我们开发的应用基本都是面向中文用户的,所以需要对项目进行本地化,今天正好借着这个入门项目给大家介绍下如何在 Go Web 应用中进行国际化和本地化编程,由于项目比较简单,我们只介绍消息提示、视图模板和日期格式的本地化,更多本地化实现留待后面本地化专题详细介绍。
学院君
2020/04/17
2K0
组件分享之后端组件——国际化组件go-i18n
近期正在探索前端、后端、系统端各类常用组件与工具,对其一些常见的组件进行再次整理一下,形成标准化组件专题,后续该专题将包含各类语言中的一些常用组件。欢迎大家进行持续关注。
cn華少
2022/03/06
8720
Vue-i18n 国际化
上边写的当前的语言切换是默认的状态,初始化的时候一定加载的是默认的,比如默认的是中文,无论你后期改成什么状态,最后重新加载时一定是中文
全栈程序员站长
2022/08/15
7730
Vue-i18n 国际化
Nuxt3+vue-i18n国际化(巨坑!!
Nuxt3 据说是提供了 一个@nuxtjs/i18n@nextnuxtjs/i18n官网 。官方文档有提供引入和使用方法。
KID.
2023/11/02
3.5K5
jQuery.i18n.properties 实现 Web 前端的国际化
国际化英文单词为:Internationalization,又称 i18n,“i”为单词的第一个字母,“18”为“i”和“n”之间单词的个数,而“n”代表这个单词的最后一个字母。
江米小枣
2020/06/15
4.8K1
vuejs国际化插件vue-i18n的使用
在web开发中,国际化大部分情况是不用考虑的,因为大部分人开发的软件程序都只是给一小部分相同语言人用的。
zhangheng
2020/04/28
2.3K0
Spring i18n国际化
随着互联网的发展,越来越多的企业和个人开始关注全球化的需求。在这个背景下,多语言支持成为了一个重要的课题。Spring框架作为一款优秀的Java开发框架,提供了丰富的i18N支持,能帮助搬砖工快速实现多语言应用。
鱼找水需要时间
2023/06/20
3430
Spring i18n国际化
vue-i18n国际化语言在项目中的使用
前端国际化:应用要服务于不同的地区的用户,所以应用不能单一语言;应用要能让不同地区的人无障碍使用就需要实现国际化。 目前在各大商城项目中,对于国际化语言的需求越来越高了,其中最多的就是vue项目使用i18n插件实现多语言切换功能,最近有幸我刚好做了这方面的业务,下面是我对vue-i18n国际化语言的一点总结与记录
CRMEB商城源码
2022/08/12
1.3K0
Next.js 实战 (四):i18n 国际化的最优方案实践
有关 Next.js 国际化的方案网上很多,而且各部相同,但大部分的方案都是在 /app 目录下添加动态路由 [lang] 这样的形式,这不是我想要的效果。
白雾茫茫丶
2024/12/11
7131
Next.js 实战 (四):i18n 国际化的最优方案实践
使用dropwizard(6)-国际化-easy-i18n
前言 Dropwizard官方文档并没有提供国际化的模块,所以只能自己加。Spring的MessageResource用的很顺手,所以copy过来。 Easy i18n 在整合Dropwizard的时候,多语言貌似只能通过jdk自带的ResourceBundle拿数据。其实也就够了,但在开发过程中发现需要缓存,需要解析占位符等。代码越写越多,显然不是仅仅一个调用就完事的。写的差不多的时候突然觉得和spring context里的message source结构类似。于是,放弃维护已经开始变的复杂的逻辑,直
Ryan-Miao
2018/03/14
1.2K0
使用dropwizard(6)-国际化-easy-i18n
springboot-i18n国际化
In computing, internationalization and localization are means of adapting computer software to different languages, regional peculiarities and technical requirements of a target locale.
用户2146693
2019/08/08
1.4K0
springboot-i18n国际化
Vue I18n 在 Vuetify 项目中使用
http://kazupon.github.io/vue-i18n/zh/introduction.html
草帽lufei
2022/07/29
1.6K0
Vue I18n 在 Vuetify 项目中使用
Vue项目i18n国际化语言切换
本篇分两部分,第一部分为vue+i18n国际化,第二部分是怎样适配element的国际化,第三部分为使用方法 效果预览 源码参考 第一部分:Vue+i18n 1.安装依赖 npm install
RtyXmd
2019/04/23
2.9K0
Vue项目i18n国际化语言切换
Golang国际化(i18n)和本地化(l10n)指南
Go is a statically compiled language that gained a lot of popularity lately due to the fact that is simple, performant and fits really well with developing cloud applications. It has a strong, yet poorly documented sub-package level base library that deals with a lot of aspects related to internationalization (i18n) and localization (l10n), such as character encodings, text transformations, and locale-specific text handling. Let's see what we can do to master this library and make our Go applications locale aware.
李海彬
2018/07/26
5.7K1
Golang国际化(i18n)和本地化(l10n)指南
vue国际化vue-i18n简单使用
之前一直想做个国际化、在线换肤和拖拉拽生成网页的demo,或者说实现思路。拖拉拽生成网页一直没什么思路,今天先实现国际化。当然是直接用插件了,并不是自己实现
wade
2020/09/14
9510
vue国际化vue-i18n简单使用
c++使用icu国际化(i18n)
International Components for Unicode,https://github.com/unicode-org/icu.git https://icu.unicode.org/ 帮助文档: https://unicode-org.github.io/icu/userguide/icu/howtouseicu.html
sofu456
2022/12/29
1.3K0
c++使用icu国际化(i18n)
Easy Vue 国际化 - Vue I18n 插件教程
在当今全球化的世界中,对于web开发人员来说,创建可为来自不同地区和文化的用户轻松实现本地化的应用程序至关重要。Vue.js 是一个流行的 JavaScript 框架,它提供了一个名为 Vue I18n 的强大国际化(i18n)插件。在本文中,我们将逐步探讨使用 Vue I18n 插件实现 Vue 应用程序国际化的过程。无论您是经验丰富的 Vue 开发人员还是刚刚入门,本指南都将帮助您快速掌握如何轻松创建多语言应用程序。。
用户4235284
2023/11/01
8300
python国际化(i18n)和中英文切
Python通过gettext模块支持国际化(i18n),可以实现程序的多语言界面的支持,下面是我的多语言支持实现:
py3study
2020/01/06
1.2K0
基于jQuery.i18n.properties 实现前端页面的资源国际化
哎_小羊
2018/01/02
4K0
基于jQuery.i18n.properties 实现前端页面的资源国际化
相关推荐
知识分享之Golang——go-i18n国际化组件
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验