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 request parameter binding and verification by Golang GinWeb

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to request parameter binding and verification of Golang GinWeb". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to request parameter binding and verification of Golang GinWeb".

Model binding and validation

Use model binding to bind the request body to a Go type. Currently supports JSON,XML,YAML and standard forms (such as foo=bar&boo=baz) binding.

Gin uses the go-playground/validator/v10 package to validate the request. For more information on the use of tags in authentication, see https://godoc.org/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags)

Note: before binding, make sure that the field tag to be bound in the structure is the same as the binding type, for example, bind JSON, set the tag: json: "fieldname"

Gin provides two ways (types) to complete the binding:

Must bind

1. Methods: Bind, BindJSON, BindXML, BindQuery, BindYAML, BindHeader

two。 Features: the underlying layer of these methods uses the MustBindWith method. If a binding error occurs, the request returns a failure message with a status code of 400: c.AbortWithError (400, err) .SetType (ErrorTypeBind), and the Content-Type header is set to text/plain; charset=utf-8 in the response. If you set the response code manually, it will warn that the response header has been set, such as prompt: [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422, if you want to better control these behaviors, it is recommended to use the corresponding ShoudBind method below.

Should bind

1. Methods: ShouldBind, ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML, ShouldBindHeader

two。 Features: the underlying layer of these methods uses ShouldBindWith. If there are binding errors, errors will be returned, developers can control and properly handle these errors.

When using the binding method, Gin attempts to automatically infer the binder to use from the type header Content-Type header. If you have identified the type that needs to be bound, you can use the underlying MustBindWith or ShouldBindWith method directly.

You can also specify a required tag value for a special field, if a field specifies the: binding: "required" tag, but an error will be returned if the field is empty when bound.

Bind the JSON as follows:

Package main import ("github.com/gin-gonic/gin"net/http") / / Binding from JSON type Login struct {User string `form: "user" json: "user" xml: "user" binding: "required" `/ / define form,json,xml respectively Binding and other tags / / Password string `form: "password" json: "password" xml: "password" binding: "required" `Password string `form: "password" json: "password" xml: "password" binding: "-" `} func main () {router: = gin.Default () / / Example for binding JSON ({"user": "manu", "password": "123"}) router.POST ("/ loginJSON") Func (c * gin.Context) {var json Login if err: = c.ShouldBindJSON (& json) Err! = nil {c.JSON (http.StatusBadRequest, gin.H {"error": err.Error ()}) return} if json.User! = "manu" | | json.Password! = "123" {c.JSON (http.StatusUnauthorized, gin.H {"status": "unauthorized"}) return} c.JSON (http.StatusOK Gin.H {"status": "you are logged in"}) / / Example for binding XML (/ / user / / 123 / /) router.POST ("/ loginXML", func (c * gin.Context) {var xml Login if err: = c.ShouldBindXML (& xml) Err! = nil {c.JSON (http.StatusBadRequest, gin.H {"error": err.Error ()}) return} if xml.User! = "manu" | | xml.Password! = "123" {c.JSON (http.StatusUnauthorized, gin.H {"status": "unauthorized"}) return} c.JSON (http.StatusOK Gin.H {"status": "you are logged in"}) / / Example for binding a HTML form (user=manu&password=123) router.POST ("/ loginForm", func (c * gin.Context) {var form Login / / This will infer what binder to use depending on the content-type header. If err: = c.ShouldBind (& form) Err! = nil {c.JSON (http.StatusBadRequest, gin.H {"error": err.Error ()}) return} if form.User! = "manu" | | form.Password! = "123" {c.JSON (http.StatusUnauthorized, gin.H {"status": "unauthorized"}) return} c.JSON (http.StatusOK Gin.H {"status": "you are logged in"}) / / Listen and serve on 0.0.0.0 Listen and serve on 8080 router.Run (": 8080")} / / Simulation request: curl-v-X POST http://localhost:8080/loginJSON-H 'content-type: application/json'-d'{"user": "manu", "password": "123"}'

Skip validation: corresponding to the binding: "required" tag is binding: "-", indicating that the field is not bound, so the field will not report an error if it is empty.

Custom validator

You can also register a custom validator yourself. For example code, please refer to https://github.com/gin-gonic/examples/blob/master/custom-validation/server.go)

Package main import ("net/http"time"github.com/gin-gonic/gin"github.com/gin-gonic/gin/binding"github.com/go-playground/validator/v10") / / Booking contains binded and validated data. / / the tag type Booking struct {CheckIn time.Time `form: "check_in" binding: "required,bookabledate" time_format: "2006-01-02" `/ / check-in time CheckOut time.Time `form: "check_out" binding: "required" is defined in the form structure. Gtfield=CheckIn "time_format:" 2006-01-02 "`/ / gtfield=CheckIn indicates that the checkout time must be greater than the check-in time} / / define the date verifier var bookableDate validator.Func = func (fl validator.FieldLevel) bool {date Ok: = fl.Field () .Interface (). (time.Time) / / get the field value by reflection-> convert to interface-> Type assertion (time type) if ok {today: = time.Now () if today.After (date) {/ / if the current time is after the checkIn field time, return false That is, the registration time cannot be earlier than the current time return false}} return true} func main () {route: = gin.Default () / / A pair of binding.Validator.Engine () interfaces make type assertions that the type is Validate structure. If the assertion is successful, register the custom validator with Gin internal if v, ok: = binding.Validator.Engine (). (* validator.Validate) Ok {/ /-if the key already exists, the previous validation function will be replaced. This registration method replaces existing validators with / /-this method is not thread-safe it is intended that these all be registered prior to any validation / / registration methods that are not thread-safe. Before verification starts, you need to ensure that all verifiers are successfully registered with v.RegisterValidation ("bookabledate", bookableDate)} route.GET ("/ bookable"). GetBookable) route.Run (": 8085")} func getBookable (c * gin.Context) {var b Booking if err: = c.ShouldBindWith (& b, binding.Query) Err = = nil {c.JSON (http.StatusOK, gin.H {"message": "Booking dates are valid!"})} else {c.JSON (http.StatusBadRequest Gin.H {"error": err.Error ()}} / / Simulation request: / / check-in time and checkout time meet the conditions / / $curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17" / / {"message": "Booking dates are valid!"} / the check-in time is after the checkout time Does not meet gtfield verification rules / / $curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09" / / {"error": "Key: 'Booking.CheckOut' Error:Field validation for' CheckOut' failed on the 'gtfield' tag"} / check-in time is before the current time Does not satisfy the custom validator / / $curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10" / / {"error": "Key: 'Booking.CheckIn' Error:Field validation for' CheckIn' failed on the 'bookabledate' tag"}%

In addition, the structure-level verification is registered as follows: v.RegisterStructValidation (UserStructLevelValidation, User {}), please refer to struct-lvl-validation example (https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations))

Thank you for reading, the above is the content of "how to request parameter binding and verification of Golang GinWeb". After the study of this article, I believe you have a deeper understanding of how to request parameter binding and verification of Golang GinWeb, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

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