Question

I am trying to add a custom HTTP header to the response of a certain set of controllers using Grails Filters:

class ApiFilters {
   def filters = {
      xwingFilter(uri:'/api/**') {
         after = {
            response.setHeader('X-Wing', 'foo')
         }
      }
   }
}

If the controller renders a view or text, the header gets added to the response. If the controller uses "render as JSON" the header is not added. It looks like the JSON converter is closing the output stream and sending it right away. Is that right?

I could use Grails interceptors but I'd have to replicate it in more than one controller. Any ideas on how can I achieve this?

Was it helpful?

Solution

You can do the translation from model to JSON in the filter instead of the action:

controller:

class myController {
    def myAction() {
        [aThing: 1, anotherThing: [a: 1, b: 2]]
    }
}

filter:

class ApiFilters {
    def filters = {
        xwingFilter(uri:'/api/**') {
            after = { model ->
                response.setHeader('X-Wing', 'foo')
                render model as JSON
                return false // prevent normal view from rendering
            }
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top