2

Preface

According to user feedback, the open source project: go-gin-api GitHub stars 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.

lang.png

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.

Recommended reading


程序员新亮
2.9k 声望1.2k 粉丝

GitHub 9K+ Star,其中适合 Go 新手的开箱即用项目 go-gin-api 5.2K Star:[链接],联系我:wx-xinliang