DEV Community

loading...

Discussion on: Create API with Gin in Golang Part 3

Collapse
twocs profile image
Tom Anderson • Edited

Got to this post when investigating the difference between these two:
c.AbortWithStatusJSON and c.JSON
I think when you know that the value and we don't want any further processing, we can use c.AbortWithStatusJSON

So in general, I've been replacing all c.JSON with c.AbortWithStatusJSON in the examples like above.

The problem occurs because further processing can occur after the c.JSON calls, and if there's another c.JSON, it will also add JSON to the response stream. These two are exactly equivalent except that the c.JSON stays alive, which can trip up a developer when edge cases occur.
c.JSON(201, gin.H{"message": "Bookmark saved", "bookmark": bookmarkPayload})
c.AbortWithStatusJSON(201, gin.H{"message": "Bookmark saved", "bookmark": bookmarkPayload})

I'm preferring the second because it returns a successful status and message and stops processing.