render an empty HTTP response with Grails 3

1.6k Views Asked by At

My goal is to render an HTTP response in a Grails 3.1 controller method that has

  • a given status code (mostly 204, but potentially others, like 200)
  • no Content-Type, or Content-Encoding headers (since there is no content, right?)

render(status: 204) adds an arbitrary Content-Type: application/json header.

Furthermore, this method (see grails.artefact.controller.support.ResponseRenderer.render()) in this case invokes HttpServletResponse.sendError(), though it is not an error. Why is that?

Currently we solve this by dealing with the response directly:

response.status = statusCode.value()
response.flushBuffer()

But this prevents us from using Grails interceptors after method for doing something before the response is sent. This is why we are looking for a different way, which does not change the HTTP response (like adding a Content-Type header).

1

There are 1 best solutions below

1
Shashank Agrawal On

You can write just like:

response.status = 204
render ""

This will respond with Content-Type header as text/html;charset=utf-8. To change the content-type you can make use of Content negotiation in Grails.

To remove the Content-Type header completely, you can try response.setHeader("Content-Type", "")