跳到主要内容

添加 i18n 支持

在模块的根目录下执行以下命令生成相关配置

cvg enable i18n

以上命令会依次执行如下操作:

1.在 app/instance.go 中添加两行代码,用于保存 i18n 实例:

import "cvgo/provider/i18n"

var I18n i18n.Service

2.在模块 internal/boot/init.go 的 init() 方法中添加以下代码获取实例

import (
"cvgo/provider/i18n"
)

func init() {
app.I18n = provider.Services.NewSingle(i18n.Name).(i18n.Service)
}

3.在路由定义文件 routing.go 中添加 i18n 中间件

import (
"cvgo/provider/httpserver/middleware"
)

func Routes(engine *httpserver.Engine) {
engine.UseMiddleware(middleware.I18n())
}

4.在模块中创建 i18n/en.jsoni18n/zh.json 两个演示语言包,内容如下:

en.json
{
"hello": "ni hao",
"world": {
"china": "zhong guo"
}
}
zh.json
{
"hello": "你好",
"world": {
"china": "中国"
}
}

至此,添加 i18n 支持完成。

使用语言包

前端

前端请求接口时在 header 中带上 Language:zh
zh 为具体语言包名称(对应 zh.json),如果要使用英文则改成 Language:en。如果不传,后端默认使用 en。

后端

package api

import "cvgo/provider/httpserver"

func Index(ctx *httpserver.Context) {

ctx.Log.Debug(ctx.I18n.Get("hello"))
ctx.Log.Debug(ctx.I18n.Get("world.china"))

ctx.Resp.Text("Index")
}

提示

语言包会在第一次从磁盘加载后缓存在内存中,不会每次 http 请求都去磁盘加载。