当前位置:网站首页>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 intomap[string]interface{}
type , And then usemapstructure
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 '_' Surenotes : 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
边栏推荐
- 20220215 CTF misc buuctf Xiaoming's safe binwalk analysis DD command separate rar file archpr brute force password cracking
- CentOS installation starts redis
- The principle of journal node
- P4 learning - p4runtime
- CMU15445 (Fall 2019) 之 Project#1 - Buffer Pool 详解
- Basic knowledge of Embedded Network - introduction of mqtt
- leetcode 474. Ones and zeroes (medium)
- 2022-2028 global herbal diet tea industry research and trend analysis report
- 问题解决:如何管理线程私有(thread_local)的指针变量
- MySQL storage engine
猜你喜欢
20220215-ctf-misc-buuctf-ningen--binwalk analysis --dd command separation --archpr brute force cracking
20220215 misc buctf easycap Wireshark tracks TCP flow hidden key (use of WinHex tool)
写给 5000 粉丝的一封信!
PyTorch安装并使用gpu加速
20220215 CTF misc buuctf Xiaoming's safe binwalk analysis DD command separate rar file archpr brute force password cracking
SAP ui5 beginner tutorial 19 - SAP ui5 data types and complex data binding
优质的水泵 SolidWorks模型素材推荐,不容错过
魔王冷饭||#101 魔王解惑数量多与质量;员工管理;高考志愿填报;游戏架构设计
Oracle temporary table explanation
Redis - cache penetration, cache breakdown, cache avalanche
随机推荐
Cmu15445 (fall 2019) project 1 - buffer pool details
[2023 MediaTek approved the test questions in advance] ~ questions and reference answers
Multi graph explanation of resource preemption in yarn capacity scheduling
2022-2028 global capsule shell industry research and trend analysis report
运动与健康
Vulnerability discovery - App application vulnerability probe type utilization and repair
Implementation of date class
2022就要过去一半了,挣钱好难
ArrayList分析1-循环、扩容、版本
The communication mechanism and extension of Supervisor
What is product thinking
Authentication principle of Ranger plug-in
Member management applet actual development 07 page Jump
连表查询 select 生成
Set different background colors for the border and text of the button
Can SQL execution be written in tidb dashboard
Two-stage RO: part 1
Interface documentation system - Yapi
最长的可整合子数组的长度
C # Generate PPK files in Putty format (passthrough support)