Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement golan Parameter check Validator

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to achieve golan parameter check Validator, the article is very detailed, has a certain reference value, interested friends must read it!

1. Practice

Go get github.com/go-playground/validator/v10

Define the knot:

Type UserInfo struct {ID int `validate: "gt=0" `Age int `validate: "gt=0" `Name string `validate: "required" `Sex string `validate: "required" `}

Initialize the structure and verify the parameters:

Func InitUserInfo (id,age int,name,sex string) * UserInfo {/ / new A verifier valid: = validator.New () / / initialize UserInfo userInfo: = & UserInfo {ID: id, Age: age, Name:name, Sex:sex,} if err: = valid.Struct (userInfo); err! = nil {fmt.Println ("Parameter verification fails", err)} return userInfo}

Effect:

InitUserInfo (1InitUserInfo 2, "kevin", "male") / / Parameter check passed InitUserInfo (0Magne2, "kevin", "male") / / Parameter check failed Key: 'UserInfo.ID' Error:Field validation for' ID' failed on the 'gt' tagInitUserInfo (1Magne2, "kevin", ") / / Parameter check failed Key:' UserInfo.Sex' Error:Field validation for 'Sex' failed on the' required' tag

If the parameter verification fails, the err will contain the failed field information.

1.1 check label

Skip this field and do not take a test

| |: apply multiple restrictions, only need to satisfy one of them, such as rgb | rgba |

Required: field must be set and cannot be default

Omitempty: if the field is not set, ignore it

1.2 string constraint

Excludesall: does not contain any UNICODE characters in the parameter, such as excludesall=ab

Excludesrune: does not contain rune characters represented by parameters, excludesrune=asong

Startswith: prefixed with parameter substring, such as startswith=hi

Endswith: suffixed with a parameter substring, such as endswith=bye.

Contains=: contains parameter substrings, such as contains=email

Containsany: contains any UNICODE character in the parameter, such as containsany=ab

Containsrune: contains rune characters represented by parameters, such as `containsrune=asong

Excludes: does not contain parameter substrings, such as excludes=email

1.3 Custom verifier

Support the implementation of custom check tags in Gin

Define check logic:

/ / sum cannot be greater than 10func VerifySum (level validator.FieldLevel) bool {if sum,ok: = level.Field (). Interface (). (int); ok {fmt.Println (sum) if sum > 10 {return false} return true} return false}

Registration label:

/ / register if vQuery ok: = binding.Validator.Engine (). (* validator.Validate); ok {if err: = v.RegisterValidation ("sum", VerifySum); err! = nil {fmt.Println ("parameter verification tag registration failed")} fmt.Println ("parameter verification tag registration successful")}

Apply tags to the structure:

Type TestSum struct {Sum int `binding: "sum" `}

Test:

Func getSum (c * gin.Context) {var b TestSum b.Sum = cast.ToInt (c.Request.URL.Query (). Get ("sum")) / / data model binding query string verification if err: = c.ShouldBindWith (& b, binding.Query) Err = = nil {c.JSON (http.StatusOK, gin.H {"message": "prams are valid!"})} else {c.JSON (http.StatusBadRequest, gin.H {"error": err.Error ()})} func main () {route: = gin.Default () / / register if v field ok: = binding.Validator.Engine (). (* validator.Validate); ok {if err: = v.RegisterValidation ("sum", VerifySum) Err! = nil {fmt.Println ("Parameter verification tag registration failed")} fmt.Println ("parameter verification tag registration succeeded")} route.GET ("/ getSum", getSum) route.Run (": 8080")}

Attach:

The tag value in Go is obtained through reflection:

Type TestSum struct {Sum int `binding: "sum" `} / / get the tag value: var b TestSum b_type: = reflect.TypeOf (b) fmt.Println (b_type.Field (0). Tag.Get ("binding")) these are all the contents of the article "how to implement golan parameter verification Validator". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report