Preface
According to user feedback, the open source project: go-gin-api adds two small functions.
Two small functions are related to language packs:
- Function 1: The error message returned by the interface supports both Chinese and English;
- Function 2: The error message of parameter verification supports both Chinese and English;
My implementation method is to select language when the project is installed, and then output the corresponding Chinese and English according to the selected language in the project, as shown in the figure below.
The error message returned by the interface supports both Chinese and English
Code location
Project code location: internal/pkg/code
How to use
// 与原来使用方式一致
code.Text(code.ServerError)
Error message customization
- Chinese: internal/pkg/code/zh-cn.go
- English: internal/pkg/code/en-us.go
If you want to add/edit error messages, just operate in the corresponding file.
The error message of parameter verification supports both Chinese and English
Code location
Project code location: internal/pkg/validation
How to use
req := new(createRequest)
if err := ctx.ShouldBindForm(req); err != nil {
fmt.Println(validation.Error(err))
}
Error message language pack
The error message language pack uses go-playground/validator
- Chinese: v10/translations/zh
- English: v10/translations/en
Example
Username string `form:"username" binding:"required"` // 用户名
Nickname string `form:"nickname" binding:"required"` // 昵称
unused language pack
// 错误信息
createRequest.Username' Error:Field validation for 'Username' failed on the 'required' tag\nKey: 'createRequest.Nickname' Error:Field validation for 'Nickname' failed on the 'required' tag"
uses Chinese language pack
// 错误信息
Username为必填字段;Nickname为必填字段;
use English language pack
// 错误信息
Username is a required field;Nickname is a required field;
summary
The above, I hope it can help you, the code has been submitted to GitHub, download the latest code and use it.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。