How to Handle JSON Request and Response in Gin

Web
Handle JSON in Gin using ShouldBindJSON for requests and c.JSON for responses.

Use gin.BindJSON to decode the request body into a struct and c.JSON to send a JSON response.

type Request struct { Name string }
type Response struct { Message string }

func handler(c *gin.Context) {
    var req Request
    if err := c.ShouldBindJSON(&req); err != nil {
        c.JSON(400, gin.H{"error": err.Error()})
        return
    }
    c.JSON(200, Response{Message: "Hello " + req.Name})
}