内置国际化i18n支持, 若你有多语言需求, 这将是一个很棒的解决方案
!> proto中的validate暂时不支持, 默认是英文
多语言的映射关系存放在internal/server/middleware/locales
en.yml
- 英文too.many.requests: 'too many requests, please try again later' data.not.change: 'data has not changed' duplicate.field: 'duplicate field' record.not.found: 'record not found' no.permission: 'no permission to access this resource' login.incorrect.password: 'incorrect password' login.same.password: 'same password' login.invalid.captcha: 'invalid captcha' login.failed: 'incorrect username or password' login.user.locked: 'user is locked' action.keep.least.one.action: 'keep at least one action' user.delete.yourself: 'you cannot delete yourself' jwt.token.missing: 'token is missing' jwt.token.invalid: 'token is invalid' jwt.token.expired: 'token has expired' jwt.token.parse.failed: 'fail to parse token' jwt.wrong.signing.method: 'wrong signing method' idempotent.token.missing: 'idempotent token is missing' idempotent.token.invalid: 'idempotent token is invalid'
zh.yml
- 中文too.many.requests: '请求频繁, 请稍候重试' data.not.change: '数据没有发生变化' duplicate.field: '字段重复' record.not.found: '记录不存在' no.permission: '无权访问' login.incorrect.password: '密码错误' login.same.password: '密码一致' login.invalid.captcha: '验证码过期' login.failed: '用户名或密码错误' login.user.locked: '用户已锁定' action.keep.least.one.action: '至少保留一个行为' user.delete.yourself: '禁止删除自己' jwt.token.missing: '缺少jwt签名' jwt.token.invalid: 'jwt签名无效' jwt.token.expired: 'jwt签名过期' jwt.token.parse.failed: '无法解析jwt签名' jwt.wrong.signing.method: 'jwt签名算法不匹配' idempotent.token.missing: '缺少幂等性签名' idempotent.token.invalid: '幂等性签名无效'
?> 在这里找你想要的语言
common/middleware/i18n
, 一行代码即可搞定
import (
"auth/api/reason" // auth是项目名
"github.com/go-cinch/common/middleware/i18n"
)
func jwt(c *conf.Bootstrap, client redis.UniversalClient) func(handler middleware.Handler) middleware.Handler {
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (rp interface{}, err error) {
...
err = reason.ErrorUnauthorized(i18n.FromContext(ctx).T(biz.JwtMissingToken))
...
}
}
}
?>参见auth.Permission, internal/biz
和internal/data
都有使用案例, 自己去发掘啦~
!> 必须使用FromContext(ctx)
, 从上下文获取当前语言, 若不存在, 默认使用configs/config.yml
中server.language
配置
开启auth服务简单测试下
# 无参数, 使用系统默认值
curl http://127.0.0.1:6060/info
# {"code":401, "reason":"UNAUTHORIZED", "message":"token is missing", "metadata":{}}
# Accept-Language参数为中文
curl -H "Accept-Language: zh" http://127.0.0.1:6060/info
# {"code":401,"reason":"UNAUTHORIZED","message":"缺少jwt签名","metadata":{}}
# 或
curl -H "Accept-Language: zh-CN,zh;q=0.9" http://127.0.0.1:6060/info
# {"code":401,"reason":"UNAUTHORIZED","message":"缺少jwt签名","metadata":{}}