2

I'm using the gin framework and the following code works fine for me

import (
    "github.com/gin-gonic/gin"
    "net/http"
)

type RequestBody struct {
    MyRequiredField string `json:"myRequiredField" binding:"required"`
}

func Handle(context *gin.Context) {
    var requestBody RequestBody

    err := context.ShouldBindJSON(&requestBody)

    if err != nil {
        context.JSON(http.StatusBadRequest, err.Error())

        return
    }

    // ...
}

I would like to know how I can tell gin that the given struct must be the request body. It must not search for fields in the route parameters or queries.

So is there a way to be more explicit, e.g.

err := context.BindStructToRequestBody(&requestBody)
baitendbidz
  • 187
  • 3
  • 19
  • Are you saying that `ShouldBindJSON`, on top of binding the request's JSON, as its name suggests, also binds the request's route and query parameters into your struct? – mkopriva Sep 04 '22 at 17:43
  • @mkopriva no, sorry, I don't. I didn't test it but the docs didn't mention that this function only binds the request body. So I don't know how Gin knows what to choose – baitendbidz Sep 04 '22 at 17:59
  • It doesn't mention it because generally in HTTP you send JSON payloads in the body and never in the route or query parameters. One can imagine using query parameters to send JSON for GET requests but that smells of bad code. So I'd say, given the widespread convention, it ought to be safe to expect that a tool that provides a method named `ShouldBindJSON`, will not try to bind anything but JSON, and it won't look for that JSON anywhere but in the body. Fingers crossed. – mkopriva Sep 04 '22 at 18:23

0 Answers0