您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何在gin框架中利用結構體來獲取參數(shù)”,在日常操作中,相信很多人在如何在gin框架中利用結構體來獲取參數(shù)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何在gin框架中利用結構體來獲取參數(shù)”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
我們在寫http請求的時候都會遇到后端的Handler是如何來接受請求的參數(shù),我們在請求的時候有表單請求,ajax請求(參數(shù)是json),如下:
http://localhost:8080/bind?name=tim&age=1
在gin框架中我們是怎么利用結構體來獲取參數(shù)呢? 其實很簡單我們直接看代碼
engine.GET("/bind", handler.BindHandler) package handler import ( "fmt" "github.com/gin-gonic/gin" ) // 定義結構體 type Member struct { Name string `form:"name"` Age int `form:"age"` } func BindHandler(c *gin.Context) { m := &Member{} c.Bind(m) fmt.Println(m) c.JSON(200, gin.H{ "code": "ok", }) }
就是利用Bind函數(shù)將參數(shù)和結構體進行綁定
// 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) }
Bind的注釋可以看出如何綁定和綁定的格式和Content-Type有很大的關系,從源碼可以看出有很多類型格式的數(shù)據(jù)都都可以進行綁定
// BindJSON is a shortcut for c.MustBindWith(obj, binding.JSON). func (c *Context) BindJSON(obj interface{}) error { return c.MustBindWith(obj, binding.JSON) } // BindXML is a shortcut for c.MustBindWith(obj, binding.BindXML). func (c *Context) BindXML(obj interface{}) error { return c.MustBindWith(obj, binding.XML) } // BindQuery is a shortcut for c.MustBindWith(obj, binding.Query). func (c *Context) BindQuery(obj interface{}) error { return c.MustBindWith(obj, binding.Query) } // BindYAML is a shortcut for c.MustBindWith(obj, binding.YAML). func (c *Context) BindYAML(obj interface{}) error { return c.MustBindWith(obj, binding.YAML) } // BindHeader is a shortcut for c.MustBindWith(obj, binding.Header). func (c *Context) BindHeader(obj interface{}) error { return c.MustBindWith(obj, binding.Header) } // 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 }
到此,關于“如何在gin框架中利用結構體來獲取參數(shù)”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。