golang gin绑定json(ShouldBindJSON)

绑定json(ShouldBindJSON)

func main() {
   router := gin.Default()

   router.POST("/loginJSON", func(c *gin.Context) {
      var json Login
      if err := c.ShouldBindJSON(&json); err != nil {
         c.JSON(http.StatusBadRequest, gin.H{"error": "Login information is not complete"})
         return
      }

      if json.User != "manu" || json.Password != "123" {
         c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
         return
      }

      c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
   })

   router.Run(":8080")
}

type Login struct {
   User     string `form:"user" json:"user" xml:"user"  binding:"required"`
   Password string `form:"password" json:"password" xml:"password" binding:"required"`
}
Share