The following request works properly for the below code.
curl -X POST localhost:5005/user --data '{"name":"Neel", "email":"[email protected]" }' -H "Content-Type:application/json" -H "Authorization:Bearer <AuthToken>"
type User struct {
Name string `gorethink:"name" json:"name"`
Email string `gorethink:"email" json:"email" binding:"required"`
}
func CreateUser(c *gin.Context) {
var user User
if c.BindJSON(&user) == nil {
fmt.Println("Name", user.Name)
fmt.Println("Email", user.Email)
saveUser(user)
}
}
How to change the above code to bind nested json. For example the request will be,
curl -X POST localhost:5005/user --data '{ "user": {"name":"Neel", "email":"[email protected]" }, "send_request":true }' -H "Content-Type:application/json" -H "Authorization:Bearer <AuthToken>"
Try
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
type User struct {
Name string `json:"name"`
Email string `json:"email" binding:"required"`
}
type JSONRequest struct {
Data User `json:"user" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/postJSON", func(c *gin.Context) {
var json JSONRequest
if c.BindJSON(&json) == nil {
fmt.Println("Name", json.Data.Name)
fmt.Println("Email", json.Data.Email)
}
c.String(200, fmt.Sprintf("%#v", json))
})
router.Run(":8080")
}
curl command:
curl -X POST -v -d "{\"user\": {\"name\": \"Bo-Yi Wu\", \"email\": \"[email protected]\"}}" localhost:8080/postJSON
Thank you. it's working.
Most helpful comment
Try
curl command: