render
render copied to clipboard
Server responds back with 200 if status set to 500
It seems there is some special handling done for accepting status and response in a predefined order. When I try to set the JSON response before setting the HTTP status, it seems the HTTP status is not updated.
if err == nil {
....
....
s := http.StatusInternalServerError
if err == nil {
s = http.StatusOK
render.JSON(w, r, response)
}
}
render.Status(r, s)
So basically, I only render JSON if it's not an error and then set status as part of common code.
But It looks like render.Status(r, s) does not work after you have done the render JSON.
The response from the server is always 200.
On Changing this to the below it seems to be working fine.
if err == nil {
....
....
s := http.StatusInternalServerError
if err == nil {
s = http.StatusOK
}
}
render.Status(r, s)
render.JSON(w, r, response)
but this now sends a zero object response even though the status code is 500
The way the library is written you are not suppose to call render.JSON directly.
You are suppose to call, render.Render(r,w,object_you_wish_to_render)
You can look at my fork for an example, but mind you my fork as a bunch of work done on it to make the library easier for me to use. Allowing me to use it a render as middle-ware, and change out the set of decoder and responders, that I want to handle the different content types. I've tried to improve the documentation a bit on it as well. (https://pkg.go.dev/github.com/gdey/[email protected])
See for an example of how you are suppose to use the library. https://github.com/gdey/chi-render/blob/v1.1.1/_examples/blog/main.go#L180
Hi, yes you need to call render.Status() (HTTP response status code) before calling render.JSON() (HTTP response body).
This is following how HTTP/1.1 works. You need to send headers before the data.
See https://pkg.go.dev/net/http#ResponseWriter.WriteHeader for more details.