您好,登錄后才能下訂單哦!
這篇文章主要講解了“Golang GinWeb框架之如何理解綁定請求字符串/URI/請求頭/復(fù)選框/表單類型”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Golang GinWeb框架之如何理解綁定請求字符串/URI/請求頭/復(fù)選框/表單類型”吧!
只綁定查詢字符串
使用SholdBindQuery方法只綁定查詢參數(shù), 而不會綁定post的數(shù)據(jù).
以下為示例代碼與模擬測試請求:
package main import ( "log" "github.com/gin-gonic/gin" ) type Person struct { Name string `form:"name"` Address string `form:"address"` } func main() { route := gin.Default() route.Any("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person // ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query) // ShouldBindQuery是c.ShouldBindWith(obj, binding.Query)方法的一個快捷綁定方法, 該方法只綁定請求字符串query string,而忽略Post提交的表單數(shù)據(jù) if c.ShouldBindQuery(&person) == nil { log.Println("====== Only Bind By Query String ======") log.Println(person.Name) log.Println(person.Address) } c.String(200, "Success") } //only bind query 模擬查詢字符串請求 //curl -X GET "localhost:8085/testing?name=eason&address=xyz" //only bind query string, ignore form data 模擬查詢字符串請求和Post表單,這里的表單會被忽略 //curl -X POST "localhost:8085/testing?name=eason&address=xyz" --data 'name=ignore&address=ignore' -H "Content-Type:application/x-www-form-urlencoded
綁定查詢字符串或Post數(shù)據(jù)(表單)
代碼與請求示例:
package main import ( "log" "time" "github.com/gin-gonic/gin" ) type Person struct { Name string `form:"name"` Address string `form:"address"` Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"` CreateTime time.Time `form:"createTime" time_format:"unixNano"` UnixTime time.Time `form:"unixTime" time_format:"unix"` } func main() { route := gin.Default() //route.GET("/testing", startPage) //使用GET route.POST("/testing", startPage) //使用POST route.Run(":8085") } func startPage(c *gin.Context) { var person Person // If `GET`, only `Form` binding engine (`query`) used. 如果路由是GET方法,則只使用查詢字符串引擎綁定 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`). // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48 //如果是POST方式, ShouldBind方法檢查請求類型頭Content-Type來自動選擇綁定引擎,比如Json/XML if c.ShouldBind(&person) == nil { log.Println(person.Name) log.Println(person.Address) log.Println(person.Birthday) log.Println(person.CreateTime) log.Println(person.UnixTime) } //if c.BindJSON(&person) == nil { // log.Println("====== Bind By JSON ======") // log.Println(person.Name) // log.Println(person.Address) //} c.String(200, "Success") } //模擬查詢字符串參數(shù)請求: //curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033" //模擬Post Json請求 //curl -X POST localhost:8085/testing --data '{"name":"JJ", "address":"xyz"}' -H "Content-Type:application/json"
綁定URI
將結(jié)構(gòu)體中標(biāo)簽指定的字段與URI中對應(yīng)的字段進(jìn)行綁定, 詳情請參考: https://github.com/gin-gonic/gin/issues/846
代碼與請求示例:
package main import "github.com/gin-gonic/gin" type Person struct { ID string `uri:"id" binding:"required,uuid"` //指定URI標(biāo)簽 Name string `uri:"name" binding:"required"` } func main() { route := gin.Default() //下面的URI中的name和id與Person結(jié)構(gòu)中的標(biāo)簽分別對應(yīng) route.GET("/:name/:id", func(c *gin.Context) { var person Person if err := c.ShouldBindUri(&person); err != nil { c.JSON(400, gin.H{"msg": err}) return } c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID}) }) route.Run(":8088") } //模擬請求 //curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3 //curl -v localhost:8088/thinkerou/not-uuid
綁定請求頭
將請求頭中的信息與結(jié)構(gòu)體綁定
package main import ( "fmt" "github.com/gin-gonic/gin" ) type testHeader struct { Rate int `header:"Rate"` //結(jié)構(gòu)中添加header標(biāo)簽 Domain string `header:"Domain"` } func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { h := testHeader{} //ShouldBindHeader是c.ShouldBindWith(obj, binding.Header)的快捷方法 if err := c.ShouldBindHeader(&h); err != nil { c.JSON(200, err) } fmt.Printf("%#v\n", h) c.JSON(200, gin.H{"Rate": h.Rate, "Domain": h.Domain}) }) r.Run() } //模擬請求 // curl -H "rate:300" -H "domain:music" http://localhost:8080/ // 參考輸出: // {"Domain":"music","Rate":300}
綁定HTML復(fù)選框
將html與main.go放到一個目錄,執(zhí)行g(shù)o run main.go運(yùn)行后, 訪問http://localhost:8080,勾選復(fù)選框,然后提交測試
main.go
package main import ( "github.com/gin-gonic/gin" ) type myForm struct { Colors []string `form:"colors[]"` //標(biāo)簽中的colors[]數(shù)組切片與html文件中的name="colors[]"對應(yīng) } func main() { r := gin.Default() //LoadHTMLGlob采用通配符模式匹配HTML文件,并將內(nèi)容進(jìn)行渲染,提供給前端訪問 r.LoadHTMLGlob("*.html") r.GET("/", indexHandler) r.POST("/", formHandler) r.Run(":8080") } func indexHandler(c *gin.Context) { c.HTML(200, "form.html", nil) } func formHandler(c *gin.Context) { var fakeForm myForm c.Bind(&fakeForm) //Bind方法根據(jù)請求頭類型Content-Type, 自動選擇合適的綁定引擎,如Json/XML c.JSON(200, gin.H{"color": fakeForm.Colors}) } //將html與main.go放到一個目錄,執(zhí)行g(shù)o run main.go運(yùn)行后, 訪問http://localhost:8080,勾選復(fù)選框,然后提交測試
form.html
使用ShouldBind方法結(jié)合結(jié)構(gòu)體標(biāo)簽, 以及mime/multipart包完成多部分類型表單數(shù)據(jù)multipart/form-data或URL編碼類型表單application/x-www-form-urlencoded數(shù)據(jù)進(jìn)行綁定:
package main import ( "github.com/gin-gonic/gin" "mime/multipart" "net/http" ) type ProfileForm struct { Name string `form:"name" binding:"required"` Avatar *multipart.FileHeader `form:"avatar" binding:"required"` // or for multiple files // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"` } func main() { router := gin.Default() router.POST("/profile", func(c *gin.Context) { // you can bind multipart form with explicit binding declaration: 可以使用顯示申明的方式,即用ShouldBindWith(&from, binding.Form)方法來綁定多部分類型表單multipart form // c.ShouldBindWith(&form, binding.Form) // or you can simply use autobinding with ShouldBind method: var form ProfileForm // in this case proper binding will be automatically selected // 這里使用ShouldBind方法自動選擇綁定器進(jìn)行綁定 if err := c.ShouldBind(&form); err != nil { c.String(http.StatusBadRequest, "bad request") return } //保存上傳的表單文件到指定的目標(biāo)文件 err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename) if err != nil { c.String(http.StatusInternalServerError, "unknown error") return } // db.Save(&form) c.String(http.StatusOK, "ok") }) router.Run(":8080") } //模擬測試: //curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile
感謝各位的閱讀,以上就是“Golang GinWeb框架之如何理解綁定請求字符串/URI/請求頭/復(fù)選框/表單類型”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Golang GinWeb框架之如何理解綁定請求字符串/URI/請求頭/復(fù)選框/表單類型這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。