Search

Dark theme | Light theme

December 23, 2015

Ratpacked: Add Response Time To Response Header

Ratpack has the class ratpack.handling.ReponseTimer which adds a header with the name X-Response-Time to the response. The value is the time spent in code from when the request comes in and the response is sent out. ResponseTimer is a handler we can add in our application. Alternatively we can use the static method decorator to get a handler decorator. With a handler decorator we can use the registry to add handler logic in our application.

First we use the ResponseTimer as a handler:

@Grab("io.ratpack:ratpack-groovy:1.1.1") 
import ratpack.handling.ResponseTimer

import static ratpack.groovy.Groovy.ratpack 

ratpack { 
    handlers { 
        // Add ResponseTimer for 
        // all requests. 
        all(new ResponseTimer())

        get { 
            render "Ratpack rocks!" 
        } 
    } 
} 

We get the same result if we add the handler decorator via the registry:

@Grab("io.ratpack:ratpack-groovy:1.1.1") 
import ratpack.handling.ResponseTimer

import static ratpack.groovy.Groovy.ratpack 

ratpack { 
    bindings {
        // Add ResponseTimer for 
        // all requests. 
        bindInstance(ResponseTimer.decorator())
    }
    handlers { 
        get { 
            render "Ratpack rocks!" 
        } 
    } 
} 

When we make a request and look at the response header we see a header with the name X-Response-Time:

$ http localhost:5050
HTTP/1.1 200 OK
X-Response-Time: 1.00000
connection: keep-alive
content-encoding: gzip
content-type: text/plain;charset=UTF-8
transfer-encoding: chunked

Ratpack rocks!

$

Written with Ratpack 1.1.1.