其实本质是将c中的request中的body数据解析到form中。
package main import ( "github.com/gin-gonic/gin" "net/http" "fmt" ) type Login struct { User string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"` Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"` } func main() { router := gin.Default() // Form 绑定普通表单的例子 // Example for binding a HTML form (user=hanru&password=hanru123) router.POST("/loginForm", func(c *gin.Context) { var form Login //方法一:对于FORM数据直接使用Bind函数, 默认使用使用form格式解析,if c.Bind(&form) == nil // 根据请求头中 content-type 自动推断. if err := c.Bind(&form); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } if form.User != "hanru" || form.Password != "hanru123" { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) return } c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) }) router.Run(":8080") }
package main import ( "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" ) type Login struct { User string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"` Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"` } func main() { router := gin.Default() router.POST("/login", func(c *gin.Context) { var form Login //方法二: 使用BindWith函数,如果你明确知道数据的类型 // 你可以显式声明来绑定多媒体表单: // c.BindWith(&form, binding.Form) // 或者使用自动推断: if c.BindWith(&form, binding.Form) == nil { if form.User == "hanru" && form.Password == "hanru123" { c.JSON(200, gin.H{"status": "you are logged in ..... "}) } else { c.JSON(401, gin.H{"status": "unauthorized"}) } } }) router.Run(":8080") }
原文:https://www.cnblogs.com/yzg-14/p/13143851.html