I am having trouble understanding how to respond with HTTP 204 (no content) using gin.Context
.
Tried context.JSON(204, nil)
or just gin.H{}
but both complain that the body is not empty.
Error #01: http: request method or response status code does not allow body
Meta: [<nil>]
Any help or pointer much appreciated!
Thanks
Comment From: matejkramny
c.Abort(204)
works but feels very wrong to be calling Abort on a request.
Comment From: petard
+1
Comment From: itsjamie
We write a 204 by using the gin.ResponseWriter in the context object.
c.Writer.WriteHeader(http.StatusNoContent)
Comment From: techjanitor
You can use Data
https://github.com/gin-gonic/gin/blob/master/context.go#L362
http://play.golang.org/p/Y0sDeUcLjv
c.Data(204, gin.MIMEHTML, nil)
Comment From: eexit
All of these work but what if I want a JSON content type anyway?
I wish there were a easier way to do this:
// Sends a JSON response with no content
c.Writer.Header().Set("Content-Type", "application/json; charset=utf-8")
c.Writer.WriteHeader(http. StatusNoContent)
Maybe a test that if c.JSON(204, nil)
is passed, it outputs nothing instead of null
.
Or make a gin.NoContent
constant?
Comment From: javierprovecho
@eexit working on it 😉
cc / @appleboy
Comment From: javierprovecho
@eexit done!
Comment From: Apologiz
@matejkramny, you can use c.Status(http.StatusNoContent)
Comment From: kuchaguangjie
So, which is preferred now ? ctx.Status(http.StatusNoContent)
?
Comment From: OhJuhun
@Apologiz c.Status() doesnt update ResponseRecorder.Code. Is it OK?
Comment From: shahzadhaider1
I had a case where I was writing tests for my handler. I was using c.Status
. Despite everything being correct and error-free, my tests were failing. Specifically, my delete handler was supposed to return a 204 status code on success, but the HTTP Response Recorder in my tests was showing a status code of 200 instead.
To resolve this, I modified the handler's return line to c.JSON(http.StatusNoContent, nil)
. After this change, the tests passed. It turns out that c.Status wasn't setting the HTTP Response Recorder's code correctly.