packagemainimport"github.com/nicksnyder/go-i18n/v2/i18n"varmessages=[]i18n.Message{{ID:"thread_not_found",Description:"Thread not exists in db",Other:"Cannot read thread",},}
其中 ID 是消息文本的唯一标识,Other 则是对应的翻译字符串(默认是英文),然后基于 goi18n 命令自动生成翻译文件到 locales 目录(执行前先创建 locales 目录):
packageconfigimport("encoding/json""github.com/nicksnyder/go-i18n/v2/i18n""golang.org/x/text/language""log""os""sync")typeAppstruct{...LocalestringLanguagestring}...typeConfigurationstruct{AppAppDbDatabaseLocaleBundle*i18n.Bundle}varconfig*Configurationvaroncesync.Once// 通过单例模式初始化全局配置
funcLoadConfig()*Configuration{once.Do(func(){file,err:=os.Open("config.json")iferr!=nil{log.Fatalln("Cannot open config file",err)}decoder:=json.NewDecoder(file)config=&Configuration{}err=decoder.Decode(config)iferr!=nil{log.Fatalln("Cannot get configuration from file",err)}// 本地化初始设置
bundle:=i18n.NewBundle(language.English)bundle.RegisterUnmarshalFunc("json",json.Unmarshal)bundle.MustLoadMessageFile(config.App.Locale+"/active.en.json")bundle.MustLoadMessageFile(config.App.Locale+"/active."+config.App.Language+".json")config.LocaleBundle=bundle})returnconfig}
所谓视图本地化指的是静态 HTML 视图模板的本地化,这里就不再适合使用消息文本翻译的方式实现了,最简单的方式就是为每个语言创建独立的视图模板进行本地化,然后在应用代码中通过读取全局配置、用户手动选择、客户端参数(比如 HTML 请求头中的 Accept-Language 字段)、或者域名信息来判断加载那种本地化视图模板,为了简化演示流程,这里我们使用全局配置的方式,也就是我们上面配置文件中设置的 Language 字段。
2.1 创建本地化视图模板
首先,我们在 views 目录下新增 en 和 zh 两个子目录,分别用于存放英文视图模板和中文视图模板,然后将原有视图文件移动到 en 目录下,并且在 zh 目录下创建每个视图模板的中文版本,以首页 index.html 为例,对应的中文版本如下: