我从gin文档中了解到,可以将json绑定到类似的结构中
type Login struct {
User string `form:"user" json:"user" binding:"required"`
Password string `form:"password" json:"password" binding:"required"`
}
func main() {
router := gin.Default()
// Example for binding JSON ({"user": "manu", "password": "123"})
router.POST("/loginJSON", func(c *gin.Context) {
var json Login
if c.BindJSON(&json) == nil {
if json.User == "manu" && json.Password == "123" {
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
} else {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
}
}
})
}
你总是需要构建一个绑定JSON的结构。 但是,如果有一个非常复杂的JSON数据,那么仅获得其中的一部分,创建一个复杂的结构便是一个很大的负担。 那可以避免id并直接解析吗?