This is the fifth day of my participation in the November Gwen Challenge. Check out the details: The last Gwen Challenge 2021

A brief introduction.

There is a joke about test engineers. It goes like this:

A test engineer walks into a bar and asks for a beer and a test engineer walks into a bar and asks for a cup of coffee and a test engineer walks into a bar and asks for 0.7 beer and a test engineer walks into a bar and asks for -1 beer and a test engineer walks into a bar, A test engineer walks into a bar and asks for a glass of foot wash a test engineer walks into a bar and asks for a glass of lizard a test engineer walks into a bar and asks for asdfQwer@24dg! A test engineer walks into a bar, walks out, enters through the window, enters through the back door, and enters through the sewer. A test engineer walks into a bar, walks out, enters in, and exits again. And I ended up beating the boss up outside and a test engineer walked into a test engineer walked into a bar and asked for a very hot muff and a test engineer walked into a bar and asked for NaN cup Null 1T and the test engineer ran into a bar, A test engineer masquerades as the owner of a bar, walks into a bar, and orders 500 beers without paying for them. 10,000 test engineers roar past the bar outside. The DROPTABLE bar test engineers left the bar satisfiedCopy the code

This joke is estimated only development can understand the joke and sad bar.

For some beginner developers, this is a nightmare. At the beginning, my code also had many faults and could not withstand such tests. Later, with more experience, the robustness of the code was gradually improved, and I understood that the parameter verification was more important.

The use of parameters can be called through the protocol interface (e.g. HTTP, RPC……) , function calls, library calls, etc.

In fact, for HTTP API requests, now many Web frameworks have built-in parameter verification function, basic use is quite cool, also need not say more.

For more common methods like function calls, many rely on the development to verify the parameters themselves. If you rely solely on comments, problems will inevitably arise during the team’s development process. At least in my opinion, never trust passed parameters!

OK, so let’s talk about Golang’s parameter validator.

Those of you who have used Gin should know that its Binding parameter validator is very handy, and that it calls the Validator. Here we take a look at the basics of validator usage and some examples of how it can be used in a typical situation.

Basic usage

1. Introduction

The validator package is available at github.com/go-playgrou… . It implements structure and value verification of individual fields based on tags and contains the following key functions:

  • Validation across fields and across structures using validation tags or custom validators
  • Slice, Array, and Map all allow validation of any or all levels of multidimensional fields
  • The ability to drill down to map keys and values for verification
  • A type interface is handled by determining its underlying type prior to validation
  • Handles custom field types
  • Allows multiple validations to be mapped to a single tag, making it structurally easier to define validation
  • Extract custom defined field names; for example, you can specify that the JSON name is extracted at validation time and made available in the result FieldError
  • Customizable I18N error messages
  • Gin Web Framework’s default validator

2. Install

go get github.com/go-playground/validator/v10
Copy the code

3. Import

import "github.com/go-playground/validator/v10"
Copy the code

4. Verify rules

Here are some examples from the various categories listed by the authorities.

1) to compare

  • Eq: equal
  • Gt: greater than
  • Gte: greater than or equal to
  • Lt: less than
  • Lte: less than or equal to
  • Ne: No

2) field

Most of the fields here can be understood as the tag of the above comparison and field stitching, while the tag with CS in the middle is the cross-struct comparison.

  • Eqfield (=Field) : must equal the value of Field
  • Nefield (=Field) : must not equal the value of Field
  • Gtfield (=Field) : must be greater than the value of Field
  • Eqcsfield (= other.field) : must equal the value of Field in struct Other

3) network

  • IP: network protocol IP address
  • Ip4_addr: indicates the IPv4 address of the network protocol
  • MAC: indicates the MAC address
  • Url: the url

4) characters

  • ASCII: ASCII
  • Boolean: the Boolean
  • Endswith:… At the end
  • The contains: contains
  • Uppercase: capital

5) format

  • Base64: base64 is a character string
  • Base64url: Base64URL Is a character string
  • Email: email the value is a character string
  • Json: json
  • JWT: JSON Web Token
  • Latitude: the latitude

6) other

  • Len: the length of the
  • Max: maximum value
  • Min: indicates the minimum value
  • Required: The field is required and cannot be empty

7) the alias

  • Iscolor: hexcolor RGB | | rgba | an HSL | hsla
  • Country_code: iso3166_1_alpha2 | iso3166_1_alpha3 | iso3166_1_alpha_numeric

Case 3.

1. Simple verification

package main

import (
	"fmt"

	"github.com/go-playground/validator/v10"
)

type User struct {
	Name           string  `validate:"required,lte=10"`                         // The name is not empty and cannot exceed 10 characters
	Age            int     `validate:"required,gte=18,lte=50"`                  // The age is not empty, the number is greater than or equal to 18, less than or equal to 50
	Email          string  `validate:"required,email"`                          // The mailbox is not empty. The format is email
	FavouriteColor string  `validate:"iscolor"`                                 / / like the color of the hexcolor RGB | | rgba | an HSL | hsla alias
	Password       string  `validate:"required,gte=16,lte=22"`                  // The password is not empty and contains 16 to 22 characters
	RePassword     string  `validate:"required,gte=16,lte=22,eqfield=Password"` // Confirm that the Password is valid and contains 16 to 22 characters. It must be the same as the Password field
	Hobbies        []Hobby `validate:"lte=5"`                                   // The number of hobbies is less than or equal to 5
}

type Hobby struct {
	Name string `validate:"lte=50"` The hobby name must contain less than or equal to 50 characters
}

var validate *validator.Validate

func main(a) {

	validate = validator.New()

	// This function validates the struct
	// No error will be reported
	validateStruct()

	// This function validates fields singly
	/ / complains
	validateVariable()

}

func validateStruct(a) {

	hobby := Hobby{
		Name: "Stroke",
	}

	user := User{
		Name:           "Zhang",
		Age:            48,
		Email:          "[email protected]",
		FavouriteColor: "#ffffff",
		Password:       "1234567890123456",
		RePassword:     "1234567890123456",
		Hobbies:        []Hobby{hobby},
	}

	err := validate.Struct(user)
	iferr ! =nil {
		fmt.Println(err)
	}

}

func validateVariable(a) {

	email := "kuari.justmylife.cc" // The format of the email address is incorrect, and an error will be reported
	err := validate.Var(email, "required,email")
	iferr ! =nil {
		fmt.Println(err)
	}

}
Copy the code

2. Customize authentication

Custom validation can create a verification function of its own:

// Register the validation function
func ValidateMyVal(fl validator.FieldLevel) bool {
	return fl.Field().String() == "hello,world!"
}
Copy the code

Then register it with validate:

validate = validator.New()
validate.RegisterValidation("is-hello", ValidateMyVal)

s := "hello,kuari" // It is different from the string in the checksum function, so an error is reported here
err := validate.Var(s, "is-hello")
iferr ! =nil {
  fmt.Println(err)
}
Copy the code

Custom verification can meet special scenarios in the development process. By formulating standard verification standards, team collaboration and development efficiency can be promoted.

4. The last

That brings us to the Validator. This article is short and can be used for simple scenarios. And the case in this paper is also based on the official case, so that it is slightly grounded. If you are interested, you are advised to take a complete look at the official documents and cases. A variety of usages can meet a variety of scenarios and ensure the robustness of the code as well as the beauty of the code.

5. Reference documents

  • go-playground/validator

Vi. Original blog

  • How does Golang validate parameters with a Validator