自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Golang GinWeb框架5-綁定請求字符串/URI/請求頭/復選框/表單類型

開發(fā) 前端
本文接著上文(Golang GinWeb框架4-請求參數(shù)綁定和驗證)繼續(xù)探索GinWeb框架

 簡介

本文接著上文(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)

以下為示例代碼與模擬測試請求:

  1. package main 
  2.  
  3. import ( 
  4.   "log" 
  5.  
  6.   "github.com/gin-gonic/gin" 
  7.  
  8. type Person struct { 
  9.   Name    string `form:"name"
  10.   Address string `form:"address"
  11.  
  12. func main() { 
  13.   route := gin.Default() 
  14.   route.Any("/testing", startPage) 
  15.   route.Run(":8085"
  16.  
  17. func startPage(c *gin.Context) { 
  18.   var person Person 
  19.   // ShouldBindQuery is a shortcut for c.ShouldBindWith(obj, binding.Query) 
  20.   // ShouldBindQuery是c.ShouldBindWith(obj, binding.Query)方法的一個快捷綁定方法, 該方法只綁定請求字符串query string,而忽略Post提交的表單數(shù)據(jù) 
  21.   if c.ShouldBindQuery(&person) == nil { 
  22.     log.Println("====== Only Bind By Query String ======"
  23.     log.Println(person.Name
  24.     log.Println(person.Address) 
  25.   } 
  26.   c.String(200, "Success"
  27. //only bind query 模擬查詢字符串請求 
  28. //curl -X GET "localhost:8085/testing?name=eason&address=xyz" 
  29.  
  30. //only bind query string, ignore form data 模擬查詢字符串請求和Post表單,這里的表單會被忽略 
  31. //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

代碼與請求示例:

  1. package main 
  2.  
  3. import ( 
  4.   "log" 
  5.   "time" 
  6.  
  7.   "github.com/gin-gonic/gin" 
  8.  
  9. type Person struct { 
  10.   Name       string    `form:"name"
  11.   Address    string    `form:"address"
  12.   Birthday   time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"
  13.   CreateTime time.Time `form:"createTime" time_format:"unixNano"
  14.   UnixTime   time.Time `form:"unixTime" time_format:"unix"
  15.  
  16. func main() { 
  17.   route := gin.Default() 
  18.   //route.GET("/testing", startPage)           //使用GET 
  19.   route.POST("/testing", startPage)  //使用POST 
  20.   route.Run(":8085"
  21.  
  22. func startPage(c *gin.Context) { 
  23.   var person Person 
  24.   // If `GET`, only `Form` binding engine (`query`) used.  如果路由是GET方法,則只使用查詢字符串引擎綁定 
  25.   // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`). 
  26.   // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48 
  27.   //如果是POST方式, ShouldBind方法檢查請求類型頭Content-Type來自動選擇綁定引擎,比如Json/XML 
  28.   if c.ShouldBind(&person) == nil { 
  29.     log.Println(person.Name
  30.     log.Println(person.Address) 
  31.     log.Println(person.Birthday) 
  32.     log.Println(person.CreateTime) 
  33.     log.Println(person.UnixTime) 
  34.   } 
  35.  
  36.   //if c.BindJSON(&person) == nil { 
  37.   //  log.Println("====== Bind By JSON ======"
  38.   //  log.Println(person.Name
  39.   //  log.Println(person.Address) 
  40.   //} 
  41.  
  42.   c.String(200, "Success"
  43. //模擬查詢字符串參數(shù)請求: 
  44. //curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033" 
  45. //模擬Post Json請求 
  46. //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

代碼與請求示例:

  1. package main 
  2.  
  3. import "github.com/gin-gonic/gin" 
  4.  
  5. type Person struct { 
  6.   ID string `uri:"id" binding:"required,uuid"`  //指定URI標簽 
  7.   Name string `uri:"name" binding:"required"
  8.  
  9. func main() { 
  10.   route := gin.Default() 
  11.   //下面的URI中的name和id與Person結(jié)構(gòu)中的標簽分別對應(yīng) 
  12.   route.GET("/:name/:id", func(c *gin.Context) { 
  13.     var person Person 
  14.     if err := c.ShouldBindUri(&person); err != nil { 
  15.       c.JSON(400, gin.H{"msg": err}) 
  16.       return 
  17.     } 
  18.     c.JSON(200, gin.H{"name": person.Name"uuid": person.ID}) 
  19.   }) 
  20.   route.Run(":8088"
  21. //模擬請求 
  22. //curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3 
  23. //curl -v localhost:8088/thinkerou/not-uuid 

綁定請求頭

將請求頭中的信息與結(jié)構(gòu)體綁定

  1. package main 
  2.  
  3. import ( 
  4.   "fmt" 
  5.   "github.com/gin-gonic/gin" 
  6.  
  7. type testHeader struct { 
  8.   Rate   int    `header:"Rate"`   //結(jié)構(gòu)中添加header標簽 
  9.   Domain string `header:"Domain"
  10.  
  11. func main() { 
  12.   r := gin.Default() 
  13.   r.GET("/", func(c *gin.Context) { 
  14.     h := testHeader{} 
  15.  
  16.     //ShouldBindHeader是c.ShouldBindWith(obj, binding.Header)的快捷方法 
  17.     if err := c.ShouldBindHeader(&h); err != nil { 
  18.       c.JSON(200, err) 
  19.     } 
  20.  
  21.     fmt.Printf("%#v\n", h) 
  22.     c.JSON(200, gin.H{"Rate": h.Rate, "Domain": h.Domain}) 
  23.   }) 
  24.  
  25.   r.Run() 
  26.  
  27. //模擬請求 
  28. // curl -H "rate:300" -H "domain:music" http://localhost:8080/ 
  29. // 參考輸出: 
  30. // {"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

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.  
  6. type myForm struct { 
  7.   Colors []string `form:"colors[]"` //標簽中的colors[]數(shù)組切片與html文件中的name="colors[]"對應(yīng) 
  8.  
  9. func main() { 
  10.   r := gin.Default() 
  11.  
  12.   //LoadHTMLGlob采用通配符模式匹配HTML文件,并將內(nèi)容進行渲染,提供給前端訪問 
  13.   r.LoadHTMLGlob("*.html"
  14.   r.GET("/", indexHandler) 
  15.   r.POST("/", formHandler) 
  16.  
  17.   r.Run(":8080"
  18.  
  19. func indexHandler(c *gin.Context) { 
  20.   c.HTML(200, "form.html", nil) 
  21.  
  22. func formHandler(c *gin.Context) { 
  23.   var fakeForm myForm 
  24.   c.Bind(&fakeForm) //Bind方法根據(jù)請求頭類型Content-Type, 自動選擇合適的綁定引擎,如Json/XML 
  25.   c.JSON(200, gin.H{"color": fakeForm.Colors}) 
  26.  
  27. //將html與main.go放到一個目錄,執(zhí)行g(shù)o run main.go運行后, 訪問http://localhost:8080,勾選復選框,然后提交測試 

form.html

  1. <form action="/" method="POST"
  2.     <p>Check some colors</p> 
  3.     <label for="red">Red</label> 
  4.     <input type="checkbox" name="colors[]" value="red" id="red"
  5.     <label for="green">Green</label> 
  6.     <input type="checkbox" name="colors[]" value="green" id="green"
  7.     <label for="blue">Blue</label> 
  8.     <input type="checkbox" name="colors[]" value="blue" id="blue"
  9.     <input type="submit"
  10. </form> 

 綁定Multipart/Urlencoded

使用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

  1. package main 
  2.  
  3. import ( 
  4.   "github.com/gin-gonic/gin" 
  5.   "mime/multipart" 
  6.   "net/http" 
  7.  
  8. type ProfileForm struct { 
  9.   Name   string                `form:"name" binding:"required"
  10.   Avatar *multipart.FileHeader `form:"avatar" binding:"required"
  11.  
  12.   // or for multiple files 
  13.   // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"
  14.  
  15. func main() { 
  16.   router := gin.Default() 
  17.   router.POST("/profile", func(c *gin.Context) { 
  18.     // you can bind multipart form with explicit binding declaration:  可以使用顯示申明的方式,即用ShouldBindWith(&from, binding.Form)方法來綁定多部分類型表單multipart form 
  19.     // c.ShouldBindWith(&form, binding.Form) 
  20.     // or you can simply use autobinding with ShouldBind method: 
  21.     var form ProfileForm 
  22.     // in this case proper binding will be automatically selected 
  23.     // 這里使用ShouldBind方法自動選擇綁定器進行綁定 
  24.     if err := c.ShouldBind(&form); err != nil { 
  25.       c.String(http.StatusBadRequest, "bad request"
  26.       return 
  27.     } 
  28.     //保存上傳的表單文件到指定的目標文件 
  29.     err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename) 
  30.     if err != nil { 
  31.       c.String(http.StatusInternalServerError, "unknown error"
  32.       return 
  33.     } 
  34.     // db.Save(&form) 
  35.     c.String(http.StatusOK, "ok"
  36.   }) 
  37.   router.Run(":8080"
  38. //模擬測試: 
  39. //curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile 

參考文檔

Gin官方倉庫:https://github.com/gin-gonic/gin

 

責任編輯:姜華 來源: 云原生云
相關(guān)推薦

2020-12-02 11:18:28

Golang GinW

2020-12-03 09:28:05

Golang GinW

2020-11-26 10:08:17

Golang GinW

2010-01-25 10:35:12

Android復選框

2009-12-31 17:26:43

Silverlight

2020-11-23 10:48:39

Golang GinW

2009-11-24 19:12:58

PHP接收復選框信息

2012-01-06 15:18:53

Java

2009-11-17 11:24:00

PHP應(yīng)用技巧

2015-07-07 10:20:47

WebCSS框架

2020-12-10 10:22:48

GinWeb中間件HTTPS

2024-01-12 10:25:51

PyQt6Python復選框

2021-10-31 23:01:50

語言拼接字符串

2009-07-09 14:56:23

Servlet讀取

2010-09-13 15:12:26

sql server字

2012-03-08 11:23:09

jQuery Mobi

2021-05-24 10:24:42

Golang字符串Python

2013-12-02 09:43:29

字符串編程

2010-03-09 15:15:02

Python字符串類型

2021-11-09 09:43:52

鴻蒙HarmonyOS應(yīng)用
點贊
收藏

51CTO技術(shù)棧公眾號