引言本文继上文(GolangGinWebFramework4-RequestParameterBindingandVerification)继续探索GinWeb框架只绑定查询字符串,使用SholdBindQuery方法只绑定查询参数,不绑定post数据。详情请参考:OnlyBindQueryString(https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017)下面是示例代码和模拟测试请求:packagemainimport("log""github.com/gin-gonic/gin")typePersonstruct{Namestring`form:"name"`Addressstring`form:"address"`}funcmain(){route:=gin.Default()route.Any("/testing",startPage)route.Run(":8085")}funcstartPage(c*gin.Context){varpersonPerson//ShouldBindQuery是一个shortcutforc.ShouldBindWith(obj,binding.Query)//ShouldBindQuery是c的一个shortcut绑定方法.ShouldBindWith(obj,binding.Query)方法,该方法只绑定请求字符串querystring,忽略Post提交的表单数据ifc.ShouldBindQuery(&person)==nil{log.Println("======OnlyBindByQueryString=====")log.Println(person.Name)log.Println(person.Address)}c.String(200,"Success")}//onlybindquery模拟查询字符串请求//curl-XGET"localhost:8085/testing?name=eason&address=xyz"//onlybindquerystring,ignoreformdata模拟查询字符串请求和Post表单,这里的表单会被忽略//curl-XPOST"localhost:8085/testing?name=eason&address=xyz"--data'name=ignore&address=ignore'-H"Content-Type:application/x-www-form-urlencodedBindingquerystringorPostdata(form)详情请参考:https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292代码和请求示例:packagemainimport("log""time""github.com/gin-gonic/gin")typePersonstruct{Namestruct`form:"name"`Addressstring`form:"address"`Birthdaytime.Time`form:"生日"time_format:"2006-01-02"time_utc:"1"`CreateTimetime.Time`form:"createTime"time_format:"unixNano"`UnixTimetime.Time`form:"unixTime"time_format:"unix"`}funcmain(){route:=gin.Default()//route.GET("/testing",startPage)//使用GETroute.POST("/testing",startPage)//使用POSTroute.Run(":8085")}funcstartPage(c*gin.Context){varpersonPerson//如果`GET`,只使用`Form`bindingengine(`query`)。如果路由是GET方法,只使用查询字符串引擎绑定//如果`POST`,首先检查`content-type`为`JSON`或`XML`,然后使用`Form`(`form-data`).//参见https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48//如果是POST,ShouldBind方法检查请求类型头Content-Type自动选择绑定引擎,例如Json/XMLifc.ShouldBind(&person)==nil{log.Println(person.Name)log.Println(person.Address)log.Println(person.Birthday)log.Println(person.CreateTime)log.Println(person.UnixTime)}//ifc.BindJSON(&person)==nil{//log.Println("======BindByJSON======")//log.Println(person.Name)//log.Println(person.Address)//}c.String(200,"Success")}//模拟查询字符串参数request://curl-XGET"localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"//模拟PostJson请求//curl-XPOSTlocalhost:8085/testing--data'{"name":"JJ","address":"xyz"}'-H“内容类型:ap"plication/json"绑定URI将结构体中标签指定的字段绑定到URI中对应的字段。详情请参考:https://github.com/gin-gonic/gin/issues/846代码和请求示例:packagemainimport"github.com/gin-gonic/gin"typePersonstruct{IDstring`uri:"id"binding:"required,uuid"`//指定URI标签Namestring`uri:"name"binding:"required"`}funcmain(){route:=gin.Default()//下面URI中的name和id分别对应Person结构中的标签。route.GET("/:name/:id",func(c*gin.Context){varpersonPersoniferr:=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-vlocalhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3//curl-vlocalhost:8088/thinkerou/not-uuid绑定请求头将请求头中的信息绑定到结构体packagemainimport("fmt""github.com/gin-gonic/gin")typetestHeaderstruct{Rateint`header:"Rate"`//给结构添加header标签Domainstring`header:"Domain"`}funcmain(){r:=gin.Default()r.GET("/",func(c*gin.Context){h:=testHeader{}//ShouldBindHeader是c.ShouldBindWith(obj,binding.Header)的快捷方式方法iferr:=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///referenceoutput://{"Domain":"music","Rate":300}bindHTMLcheckbox详情请参考:https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092,将html和main.go放在一个目录下,运行后执行gorunmain.go,访问http://localhost:8080,勾选复选框,提交测试main.gopackagemainimport("github.com/gin-gonic/gin")typemyFormstruct{Colors[]string`form:"colors[]"`//label中的colors[]数组切片对应html文件中的name="colors[]"}funcmain(){r:=gin.Default()//LoadHTMLGlob使用通配符模式匹配HTML文件,渲染内容,提供给前端t端访问r.LoadHTMLGlob("*.html")r.GET("/",indexHandler)r.POST("/",formHandler)r.Run(":8080")}funcindexHandler(c*gin.Context){c.HTML(200,"form.html",nil)}funcformHandler(c*gin.Context){varfakeFormmyFormc.Bind(&fakeForm)//Bind方法根据请求头类型Content-Type自动选择合适的绑定引擎,如Json/XMLc.JSON(200,gin.H{"color":fakeForm.Colors})}//将html与main将.go放在一个目录下,执行gorunmain.go运行,访问http://localhost:8080,勾选复选框,然后使用ShouldBind方法结合结构标签提交测试form.html,mime/multipartpackage完成更多Partial类型表单数据multipart/form-data或URL编码类型表单application/x-www-form-urlencoded数据绑定:表单数据类型请参考:https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4packagemainimport("github.com/gin-gonic/gin""mime/multipart""net/http")typeProfileFormstruct{Namestring`form:"name"绑定:"required"`Avatar*multipart.FileHeader`form:"avatar"binding:"required"`//orformmultiplefiles//Avatars[]*multipart.FileHeader`form:"avatar"binding:"required"`}funcmain(){router:=gin.Default()router.POST("/profile",func(c*gin.Context){//youcanbindmultipartformwithexplicitbindingdeclaration:可以使用显示声明方式,即使用ShouldBindWith(&from,binding.Form)方法绑定multipartformmultipartform//c.(http.StatusBadRequest,"badrequest")return}//将上传的表单文件保存到指定的目标文件中err:=c.SaveUploadedFile(form.Avatar,form.Avatar.Filename)iferr!=nil{c.String(http.StatusInternalServerError,"unknownerror")return}//db.Save(&form)c.String(http.StatusOK,"ok")})router.Run(":8080")}//模拟测试://curl-XPOST-v--formname=user--form"avatar=@./avatar.png"http://localhost:8080/profile参考文档Gin官方仓库:https://github.com/gin-gonic/杜松子酒
