Bogdan Nechyporenko
Bogdan Nechyporenko

Reputation: 1346

GoLang Gin Framework Status Code Without Message Body

I'm using GoLang and Gin Framework.

I need to respond for REST API call with 204 response code without message body.

How it is to do properly?

What I could find by digging the source code

c.JSON(204, "")

But server throws error at such case:

Error #01: http: request method or response status code does not allow body Meta: []

Any ideas?

Upvotes: 12

Views: 21812

Answers (4)

Roee Hershko
Roee Hershko

Reputation: 1

I ended up using built in render function:

c.Render(http.StatusOK, render.Data{})

Upvotes: 0

dave
dave

Reputation: 64657

You could use c.AbortWithStatus(204), with the one caveat that when you use abort, the rest of pending handlers will never be called for that request.

Or, you could do:

c.Writer.WriteHeader(204)

and let your program continue normally (but making sure not to write out anything else)

Upvotes: 16

Sathish
Sathish

Reputation: 1475

adding on @depado comments,

c.Status(http.StatusNoContent) is the simplest way to achieve this. Works with gin v1.6.3

Upvotes: 25

simon_xia
simon_xia

Reputation: 2544

up to now, the function Abort's prototype is

 func (c *Context) Abort()

you can use AbortWithStatus instead c.AbortWithStatus(204), whose prototype is

 func (c *Context) AbortWithStatus(code int)

Upvotes: 2

Related Questions