当前位置:网站首页>Golang treasure house recommendation

Golang treasure house recommendation

2022-07-01 01:01:00 Big flying siege lion

1. Let me write it first

I was in last year coding When , There are two easy-to-use libraries , Record it here , For later use , At the same time, it is also convenient for those who have the needs in this regard . Programming learning materials, click to get

  • golang map to structure The library of — 

  • golang json Verification Library — 

2. mapstructure

2.1 purpose

General  map[string]interface{} Decode to the corresponding Go In the structure .

notes :Restful api body When parsing , Generally, the standard  encoding/json  The library decodes the data into  map[string]interface{} type , And then use  mapstructure  The library converts it to Go In the structure .

​ The benefits of the above one more conversion are , When api body When definitions are incompatible , Compared with the direct definition body structure , This method will not affect the original parsing structure .

2.2 Example

A detailed introduction to the use of this library ,google In many , No more details here , Just mention the pit spot .

package main

import (
	"fmt"

	"github.com/mitchellh/mapstructure"
)

type School struct {
	name string
}

type Person struct {
	Name    string
	Address string
	Phones  []string
	XInfo   string `json:"x-info"`
	School  School
}

func DecodesExample() {
	m := map[string]interface{}{
		"name":    "xiyan",
		"address": "earth",
		"x-info":  "not-parse",
		"phones":  []string{"12345678", "87654321"}, // object type
		"school":  School{name: "xy"},               // nested structure
	}
	var p Person
	err := mapstructure.Decode(m, &p)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%#v", p)
}

func main() {
	DecodesExample()
}

 Copy code 

Output :

 mapToStruct $>go run main.go
main.Person{Name:"xiyan", Address:"earth", Phones:[]string{"12345678", "87654321"}, XInfo:"", School:main.School{name:"xy"}}
 Copy code 

2.3 Pit description

2.2 Examples in , Shows how to put a  map[stirng]interface{}  Structure , Convert to custom go structure .

  • map Can contain slice etc. object type

  • map Can include custom structue type

  • map It contains key If you include  -  If the middle line is crossed, the field will not be resolved successfully , But it includes '_' Sure

    notes : See "x-info": "not-parse" , I haven't found the reason yet , Guess with go Variable names contain letters 、 Numbers 、 Underline matters .

3. validator

3.1 purpose

stay web Data validation problems are often encountered in applications , More commonly used is the package validator. The principle is to write the verification rules in struct Corresponding fields tag in , And then get through reflection struct Of tag, Realize data verification .

3.2 Example

package main

import (
	"fmt"

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

func BasicExample() {
	type Person struct {
		Name string `json:"name" validate:"required"`
		Age  int64  `json:"age" validate:"required"`
	}
	p := Person{
		Name: "",
		Age:  18,
	}
	v := validator.New()
	err := v.Struct(p)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(p)
}

func FieldExample() {
	type Person struct {
		//  Be careful :required And nameValidator  There can only be  「,」  You can't have Spaces 
		Name string `json:"name" validate:"required,nameValidator"`
		Age  int64  `json:"age" validate:"required"`
	}

	nameValidator := func(f validator.FieldLevel) bool {
		return f.Field().String() != "xiyan"
	}

	v := validator.New()
	v.RegisterValidation("nameValidator", nameValidator)

	p := Person{
		Name: "xiyan",
		Age:  19,
	}
	err := v.Struct(p)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(p)
}

func SturctLevelExample() {
	type Person struct {
		Name string `json:"name" validate:"required"`
		Age  int64  `json:"age" validate:"required"`
	}

	structValidator := func(f validator.StructLevel) {
		p := f.Current().Interface().(Person)
		if p.Name == "xiyan" {
			f.ReportError(p.Name, "Name", "name", "name", "")

		}
		if p.Age > 80 {
			f.ReportError(p.Age, "Age", "age", "age", "")

		}
	}

	v := validator.New()
	v.RegisterStructValidation(structValidator, Person{})

	p := Person{
		Name: "xiyan",
		Age:  81,
	}
	err := v.Struct(p)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(p)
}

func main() {
	// FieldExample()
	SturctLevelExample()
}

 Copy code 

The above example consists of three parts :

  • Directly in sturcture Defined tag Partially define the verification rules — BasicExample
  • in the light of structure Of Field Field defines a specific function for verification — FieldExample
  • in the light of structure Do the verification of specific functions as a whole — SturctLevelExample

Here the author uses  SturctLevelExample  The verification method of , The problem is , The specific errors identified cannot be thrown to the upper level , The upper layer can only view the errors of the specified fields , Where the specific value is wrong cannot be identified .

notes : There are more ways than problems , Here, the wrong use is exposed , I used a dirty Treatment method , Pass the wrong field tag Field exposure , Then from the top error Fields will Tag Take out .

3.3 Pit description

Specific examples

func SturctLevelExample() {
	type Person struct {
		Name string `json:"name" validate:"required"`
		Age  int64  `json:"age" validate:"required"`
	}

	structValidator := func(f validator.StructLevel) {
		p := f.Current().Interface().(Person)
		if p.Name == "xiyan" {
			f.ReportError(p.Name, "Name", "name", "name should not equal xiyan", "")

		}
		if p.Age > 80 {
			f.ReportError(p.Age, "Age", "age", "age should not greater than 80", "")

		}
	}

	v := validator.New()
	v.RegisterStructValidation(structValidator, Person{})

	p := Person{
		Name: "xiyan",
		Age:  81,
	}
	err := v.Struct(p)
	if err != nil {
		for _, e := range err.(validator.ValidationErrors) {
			fmt.Println(e.Tag())
		}
		return
	}
	fmt.Println(p)
}

func main() {
	SturctLevelExample()
}

 Copy code 

Output :

validator $> go run main.go
name should not equal xiyan
age should not greater than 80
 Copy code 

4. twitter

Today is a good day , I hope those who work overtime can get off work early .

  • I hope you can understand , Grow up for you , You can do more things you want to do , Instead of being forced to do more things you don't want to do .
  • I hope you can live happily , Do what you like to do , When you are tired, drink and blow , Live the life you want .
  • If you like it, fight for it , Cherish what you get , Miss and forget .

One of the rules of happiness in life , When you eat, you think about whether the food tastes good ​​​​​​​​​​​​​​

原网站

版权声明
本文为[Big flying siege lion]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202160405165598.html