Golang GinWeb框架5-绑定请求字符串/URI/请求头/复选框/表单类型

开发 前端
本文接着上文(Golang GinWeb框架4-请求参数绑定和验证)继续探索GinWeb框架

 简介

本文接着上文(Golang GinWeb框架4-请求参数绑定和验证)继续探索GinWeb框架

只绑定查询字符串

使用SholdBindQuery方法只绑定查询参数, 而不会绑定post的数据. 请参考详情: 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提交的表单数据 
  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数据(表单)

详情请参考: 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. //模拟查询字符串参数请求: 
  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

将结构体中标签指定的字段与URI中对应的字段进行绑定, 详情请参考: 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结构中的标签分别对应 
  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 

绑定请求头

将请求头中的信息与结构体绑定

  1. package main 
  2.  
  3. import ( 
  4.   "fmt" 
  5.   "github.com/gin-gonic/gin" 
  6.  
  7. type testHeader struct { 
  8.   Rate   int    `header:"Rate"`   //结构中添加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放到一个目录,执行go 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[]数组切片与html文件中的name="colors[]"对应 
  8.  
  9. func main() { 
  10.   r := gin.Default() 
  11.  
  12.   //LoadHTMLGlob采用通配符模式匹配HTML文件,并将内容进行渲染,提供给前端访问 
  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方法根据请求头类型Content-Type, 自动选择合适的绑定引擎,如Json/XML 
  25.   c.JSON(200, gin.H{"color": fakeForm.Colors}) 
  26.  
  27. //将html与main.go放到一个目录,执行go 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方法结合结构体标签, 以及mime/multipart包完成多部分类型表单数据multipart/form-data或URL编码类型表单application/x-www-form-urlencoded数据进行绑定:

表单数据类型请参考: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

 

责任编辑:姜华 来源: 云原生云
相关推荐

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应用技巧

2015-07-07 10:20:47

WebCSS框架

2024-01-12 10:25:51

PyQt6Python复选框

2020-12-10 10:22:48

GinWeb中间件HTTPS

2009-07-09 14:56:23

Servlet读取

2021-10-31 23:01:50

语言拼接字符串

2010-09-13 15:12:26

sql server字

2021-05-24 10:24:42

Golang字符串Python

2021-11-09 09:43:52

鸿蒙HarmonyOS应用

2012-03-08 11:23:09

jQuery Mobi

2023-10-26 12:01:30

Golang字符串

2013-12-02 09:43:29

字符串编程
点赞
收藏

51CTO技术栈公众号