According to user feedback, two new functions are added to the open source project go gin API

Time:2021-8-30

preface

According to the feedback of users, the open source project: go gin APITwo new features.

Two small functions are related to language packs:

  • Function 1: the error information returned by the interface supports Chinese and English;
  • Function 2: the error message of parameter verification supports Chinese and English;

My implementation method is to select when installing the projectlanguageThen output the corresponding Chinese and English according to the selected language in the project, as shown in the figure below.

According to user feedback, two new functions are added to the open source project go gin API

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

Code location

Project code location: internal / PKG / code

Mode of use

//Consistent with the original 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 information, you can operate in the corresponding file.

The error message of parameter validation supports Chinese and English

Code location

Project code location: internal / PKG / validation

Mode of 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" ` // username
Nickname string ` form: "nickname" binding: "required" ` // nickname

Language pack not used

//Error message
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"

Use Chinese language pack

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

Use English language pack

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

Summary

Above, I hope it can help you. The code has been submitted to GitHub. Download the latest code and use it.

Recommended reading

  • About processing the order status flow of e-commerce system, share my technical scheme (with source code)
  • How do I write git commit message?

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]