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

Never build auth again! The Okta Developer Platform makes it simple to implement authentication, authorization, MFA and more in Java applications. Get started with the free API.

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.

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:
ratpack ,http ,groovy

Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}