1

hi i'm new to gin framework and golang and i was wondering what's the difference between Json.Unmarshal() and gin.BindJson()

in the tutorial he's building a video service which has two methods, save and findall

func (vc *videoControllerStruct) Save(ctx *gin.Context) entity.Video {
    video := entity.Video{}
    ctx.ShouldBind(&video) // ctx.BindJson(&video)
    vc.services.Save(video)
    return video

as you can see he used ctx.BindJson first and then changed it to ShouldBind (idk why) is there a way to re-write this code with json.unmarshal?

buchana
  • 23
  • 4

2 Answers2

3

ShouldBind looks like this:

func (c *Context) ShouldBind(obj any) error {
    b := binding.Default(c.Request.Method, c.ContentType())
    return c.ShouldBindWith(obj, b)
}

It basically checks for the request method and content type, and based on that, it resolves the binding. So, the incoming content can be something else than JSON.

BindJson is just an alias for MustBindWith(obj, binding.JSON) that strictly tries to unmarshal the request body to JSON. Passing any other content will produce a 400 HTTP status.

You could also use json.Unmarshal, but you'd have to explicitly access the request body in a Gin context.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
2

The main differences between json.Unmarshal and gin.BindJson are:

  • json.Unmarshal operates on raw JSON data, while gin.BindJson binds from a request body to a struct.
  • json.Unmarshal requires manually getting the JSON data ([]byte), while gin.BindJson handles getting JSON data from request transparently.
  • gin.BindJson can do extra validation and binding, while json.Unmarshal just unmarshals raw JSON.

To use json.Unmarshal with gin, you would have to do something like:

func (vc *videoController) Save(ctx *gin.Context) {

  // Get JSON data 
  var jsonData []byte
  if ctx.Request.Body != nil {
    jsonData, _ = ioutil.ReadAll(ctx.Request.Body)
  }

  // Declare video struct
  var video entity.Video

  // Unmarshal into struct
  err := json.Unmarshal(jsonData, &video)
  if err != nil {
    // handle error
  }

  // Save video 
  vc.services.Save(video)

  // Return saved video
  return video

}
TiGo
  • 652
  • 6
  • 11