preface

Based on user feedback, for open source projects:go-gin-api Two small features have been added.

Two small features are related to language packs:

  • Function 1: The error message returned by the interface supports both Chinese and English;
  • Function 2: Parameter validation error message support in English and Chinese;

My implementation method is to select the language at the time of project installation, and then output the corresponding Chinese and English in the project according to the selected language, as shown in the figure below.

The error message returned by the interface supports both English and Chinese

Code position

Project code location: internal/ PKG /code

use

// Code.text (code.serverError)

Error message customization

  • English: internal/PKG/code/useful – cn. Go
  • English: internal/PKG/code/en – us go

If you want to add/edit the error message, just do it in the corresponding file.

Parameter validation error messages in both English and Chinese

Code position

Project code location: internal/ PKG /validation

use

req := new(createRequest) if err := ctx.ShouldBindForm(req); err ! = nil { fmt.Println(validation.Error(err)) }

Error message language package

The error message language pack uses the Go-playground /validator

  • English: v10 / translations/useful
  • English: the v10 / translations/en

The sample

Username string 'form:" Username "binding:"required"' // NICKNAME

Language packs are not used

CreateTest. Username' Error:Field validation for 'Username' failed on the 'required' tag\nKey: 'createRequest.Nickname' Error:Field validation for 'Nickname' failed on the 'required' tag"

Use the Chinese Language Pack

// error message Username is required field; NICKNAME is a required field;

Use the English language package

// error message Username is a required field; Nickname is a required field;

summary

Above, hope to help you, the code has been submitted to GitHub, download the latest code to use it.

Recommended reading

  • Regarding the transfer of order status in the e-commerce system, please share my technical solution (attached source code).
  • How do I write a Git Commit message?