Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Ratpacked: Add Response Time To Response Header

DZone's Guide to

Ratpacked: Add Response Time To Response Header

Learn the two methods to add a response time to the response header.

· Java Zone ·
Free Resource

FlexNet Code Aware, a free scan tool for developers. Scan Java, NuGet, and NPM packages for open source security and open source license compliance issues.

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.

 Scan Java, NuGet, and NPM packages for open source security and license compliance issues. 

Topics:
ratpack ,http ,groovy

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}