Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails - add header to every response

How could I add a response header - say X-Time that would look something like:

X-Time: 112

Where the value given would be the time in milliseconds that the response took to process? Is there a really simple way to add this to an Grails app? Not something I want to leave on permanently but would be nice to have while developing my app.

like image 855
BuddyJoe Avatar asked Jun 20 '11 18:06

BuddyJoe


1 Answers

To simply add a header to the response, you can use an after Filter.

// grails-app/conf/MyFilters.groovy
class MyFilters {
    def filters = {
        addHeader(uri: '/*') {
            after = {
                response.setHeader('X-Time', value)
            }
        }
    }
}

Edit:

To actually compute the time, it'd probably be more proper to use a javax.servlet.Filter instead of a Grails filter.

src/groovy/com/example/myproject/MyFilter.groovy

package com.example.myproject

import javax.servlet.*

class MyFilter implements Filter {

    void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {

        def start = System.currentTimeMillis()
        chain.doFilter(request, response)

        def elapsed = System.currentTimeMillis() - start
        response.setHeader('X-Time', elapsed as String)
    }

    void init(FilterConfig config) { }
    void destroy() { }
}

src/templates/war/web.xml (run grails install-templates if src/templates isn't already in your source tree)

<filter>
  <filter-name>timer</filter-name>
  <filter-class>com.example.myproject.MyFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>timer</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

The reason for using the javax.servlet.Filter is so you don't have to separate out your "before" and "after" actions, and can therefore hold onto the start time throughout the entire filter chain & servlet execution.

Supplementary note:

To me, it seems strange to want to return the server elapsed execution time as a response header. Perhaps you have a decent reason for doing it, but in most cases I'd A) either be more concerned about total round-trip time (as observed by the client), or B) be logging elapsed execution times on the server for my own system administration/metrics purposes.

like image 83
Rob Hruska Avatar answered Oct 15 '22 09:10

Rob Hruska