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 use bind in Gin Framework

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use bind in Gin framework". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let the editor take you to learn how to use bind in the Gin framework.

Overview

In the Gin framework, there are bind functions that can easily bind the query parameters query parameter of url and the data formats submitted in http's Header,body, such as form,json,xml, to the structure of go, during which Binding does something, so many Bindding functions, how we should choose, together through the source code to unravel the mysterious veil.

Binding interface type Binding interface {Name () string Bind (* http.Request, interface {}) error}

Binding is an interface. In the source code, there are 10 structures that implement Binding and 3 interfaces.

Context.Bind// Bind checks the Content-Type to select a binding engine automatically / / Depending the "Content-Type" header different bindings are used:// "application/json"-- > JSON binding// "application/xml"-> XML binding// otherwise-- > returns an error.// It parses the request's body as JSON if Content-Type = = "application/json" using JSON or XML as a JSON input.// It decodes the json payload into the struct specified as a pointer.// It writes a 400 error and sets Content-Type header "text/plain" In the response if input is not valid.func (c * Context) Bind (obj interface {}) error {b: = binding.Default (c.Request.Method) C.ContentType () return c.MustBindWith (obj, b)} cnotext.MustBindWith// MustBindWith binds the passed struct pointer using the specified binding engine.// It will abort the request with HTTP 400 if any error occurs.// See the binding package.func (c * Context) MustBindWith (obj interface {}, b binding.Binding) error {if err: = c.ShouldBindWith (obj, b) Err! = nil {c.AbortWithError (http.StatusBadRequest, err) .SetType (ErrorTypeBind) / / nolint: errcheck return err} return nil}

As can be seen from the comments and source code, MustBindWith finally calls SouldBindWith, and judges the result of ShouldBindWith. If there is any error, it exits with the status code of http 400.

ShouldBindWith// ShouldBindWith binds the passed struct pointer using the specified binding engine.// See the binding package.func (c * Context) ShouldBindWith (obj interface {}, b binding.Binding) error {return b.Bind (c.Request, obj)}

This method is a basis for all other binding methods, and basically all binding methods need to use this method to bind a data structure.

The above is the main bingding process. Other derivatives, such as BindJSON, ShouldBindJSON, etc., are shortcuts to specific data types. They just help us to encapsulate the specific bingding data types in advance, such as the bingding function in Json format.

Context.BindJSON// BindJSON is a shortcut for c.MustBindWith (obj, binding.JSON). Func (c * Context) BindJSON (obj interface {}) error {return c.MustBindWith (obj, binding.JSON)}

Context.BindJSON analysis from the source code, you can see that only one sentence less than the Bind method

B: = binding.Default (c.Request.Method, c.ContentType ())

The purpose of this sentence is to determine the current request method and contentType to pass a specific bingding type to context.MustBindWith.

The Binding interface for the implementation of Json is as follows

Func (jsonBinding) Bind (req * http.Request, obj interface {}) error {if req = = nil | | req.Body = = nil {return fmt.Errorf ("invalid request")} return decodeJSON (req.Body, obj)}

The jsonBinding structure implements the Bind method of the Binding interface, which decodes the requested Body data and binds it to obj.

Context.ShouldBindJSON// ShouldBindJSON is a shortcut for c.ShouldBindWith (obj, binding.JSON). Func (c * Context) ShouldBindJSON (obj interface {}) error {return c.ShouldBindWith (obj, binding.JSON)}

From the source code comments, ShouldBindJSON is actually a shortcut to ShouldBindWith (obj, binding.JSON). To put it simply, parameters are fixed on ShouldBindWith (obj, binding.JSON). When we clearly specify that the parameter content submitted by body is json, it simplifies our call and enhances the readability of the code.

Context.ShouldBindUri () / / ShouldBindUri binds the passed struct pointer using the specified binding engine.func (c * Context) ShouldBindUri (obj interface {}) error {m: = make (map [string] [] string) for _, v: = range c.Params {m [v.Key] = [] string {v.Value}} return binding.Uri.BindUri (m, obj)}

The method taken from url binding is different from that of header and body. There is no need to pass in a structure type that implements the Binding interface.

Context.ShouldBindUri () / / BindUri binds the passed struct pointer using binding.Uri.// It will abort the request with HTTP 400 if any error occurs.func (c * Context) BindUri (obj interface {}) error {if err: = c.ShouldBindUri (obj); err! = nil {c.AbortWithError (http.StatusBadRequest, err) .SetType (ErrorTypeBind) / / nolint: errcheck return err} return nil}

BindUri is also an encapsulation of ShouldBindUri, with an example of judging the ShouldBindUri result.

The code is as follows

Package mainimport ("github.com/gin-gonic/gin"net/http") type queryHeader struct {Myheader string `header: "myheader" `Mydemo string `header: "mydemo" `} type queryBody struct {Name string `json: "name" `Age int `json: "age" `Sex int `json: "sex"`} type queryParameter struct {Year int `form: "year" `Month int `form: "month "`} type queryUri struct {Id int `uri:" id "`Name string `uri:" name "`} func bindUri (context * gin.Context) {var q queryUri err:= context.ShouldBindUri (& Q) if err! = nil {context.JSON (http.StatusBadRequest) Gin.H {"result": err.Error (),}) return} context.JSON (http.StatusOK,gin.H {"result": "bind successfully", "uri": Q })} func bindQuery (context * gin.Context) {var q queryParameter err:= context.ShouldBindQuery (& Q) if err! = nil {context.JSON (http.StatusBadRequest,gin.H {"result": err.Error (),}) return} context.JSON (http.StatusOK Gin.H {"result": "bind successfully", "query": Q,})} func bindBody (context * gin.Context) {var q queryBody err:= context.ShouldBindJSON (& Q) if err! = nil {context.JSON (http.StatusBadRequest,gin.H {"result": err.Error ()) }) return} context.JSON (http.StatusOK,gin.H {"result": "bind successfully", "body": Q })} func bindhead (context * gin.Context) {var q queryHeader err: = context.ShouldBindHeader (& Q) if err! = nil {context.JSON (http.StatusBadRequest,gin.H {"result": err.Error (),}) return} context.JSON (http.StatusOK Gin.H {"result": "bind successfully", "header": Q,})} func main () {srv: = gin.Default () srv.GET ("/ binding/header", bindhead) srv.GET ("/ binding/body", bindBody) srv.GET ("/ binding/query", bindQuery) srv.GET ("/ binding/:id/:name") BindUri) srv.Run (": 9999")} run result

Bind Header data

Bind QueryParameter data

Bind Body Json data

Bind Uri data

At this point, I believe you have a deeper understanding of "how to use bind in the Gin framework". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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