Golang GinWeb框架5-綁定請求字符串/URI/請求頭/復選框/表單類型
簡介
本文接著上文(Golang GinWeb框架4-請求參數(shù)綁定和驗證)繼續(xù)探索GinWeb框架
只綁定查詢字符串
使用SholdBindQuery方法只綁定查詢參數(shù), 而不會綁定post的數(shù)據(jù). 請參考詳情: Only Bind Query String(https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017)
以下為示例代碼與模擬測試請求:
- 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ù)(表單)
詳情請參考: https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292
代碼與請求示例:
- 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)體中標簽指定的字段與URI中對應(yīng)的字段進行綁定, 詳情請參考: 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標簽
- Name string `uri:"name" binding:"required"`
- }
- func main() {
- route := gin.Default()
- //下面的URI中的name和id與Person結(jié)構(gòu)中的標簽分別對應(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標簽
- 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復選框
詳情請參考:https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092,
將html與main.go放到一個目錄,執(zhí)行g(shù)o run main.go運行后, 訪問http://localhost:8080,勾選復選框,然后提交測試
main.go
- package main
- import (
- "github.com/gin-gonic/gin"
- )
- type myForm struct {
- Colors []string `form:"colors[]"` //標簽中的colors[]數(shù)組切片與html文件中的name="colors[]"對應(yīng)
- }
- func main() {
- r := gin.Default()
- //LoadHTMLGlob采用通配符模式匹配HTML文件,并將內(nèi)容進行渲染,提供給前端訪問
- 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運行后, 訪問http://localhost:8080,勾選復選框,然后提交測試
form.html
使用ShouldBind方法結(jié)合結(jié)構(gòu)體標簽, 以及mime/multipart包完成多部分類型表單數(shù)據(jù)multipart/form-data或URL編碼類型表單application/x-www-form-urlencoded數(shù)據(jù)進行綁定:
表單數(shù)據(jù)類型請參考:https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4
- 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方法自動選擇綁定器進行綁定
- if err := c.ShouldBind(&form); err != nil {
- c.String(http.StatusBadRequest, "bad request")
- return
- }
- //保存上傳的表單文件到指定的目標文件
- 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
參考文檔
Gin官方倉庫:https://github.com/gin-gonic/gin