GoLang Gin Framework Status Code Without Message Body
Asked Answered
D

4

11

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?

Duisburg answered 23/10, 2014 at 20:54 Comment(0)
S
16

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)

Surah answered 23/10, 2014 at 21:22 Comment(2)
Thanks, I was looking at Abort but didn't find it nice enough for that purpose. I like second solution! Thanks!Duisburg
Also there's now (I don't know if that's recent or not) a c.Status(code) method.Shirtwaist
O
22

adding on @depado comments,

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

Omnipotence answered 23/7, 2020 at 15:6 Comment(0)
S
16

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)

Surah answered 23/10, 2014 at 21:22 Comment(2)
Thanks, I was looking at Abort but didn't find it nice enough for that purpose. I like second solution! Thanks!Duisburg
Also there's now (I don't know if that's recent or not) a c.Status(code) method.Shirtwaist
P
2

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)
Pueblo answered 12/11, 2015 at 13:14 Comment(0)
M
0

I ended up using built in render function:

c.Render(http.StatusOK, render.Data{})
Moffit answered 3/3 at 10:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.