-
Notifications
You must be signed in to change notification settings - Fork 20
14. Gzip support
Imagine a situation where you have to send a large document over a slow connection. To make a transmission faster you can compress the document.
Let's take a look at a typical HTTP message flow that depicts this situation:
First, a client sends a request with the Accept-Encoding: gzip header that tells the server that the client supports gzip encoding.
GET /foo HTTP/1.1
Host: www.utterlyidle.com
Accept-Encoding: gzip
A server generates a response message and encodes it with gzip to produce a smaller, compressed body. Content-Length of the compressed body is calculated and Content-Encoding header is added to the response. Content-Encoding: gzip indicates to the client that gzip compression has been applied to the response body.
HTTP/1.1 200 OK
Content-Type: application/xml; charset="UTF-8"
Date: Sun, 01 Jul 2012 10:26:32 UTC
Content-Encoding: gzip
Content-Length: 280123
... gzip encoded bytes ...
Once the client receives the response it needs to decompress the message to get the original body.
Gzip is only one of many content encodings, but as it's the only one that's currently supported in Utterlyidle we don't discuss other encodings here.
To enable Gzip support in Utterlyidle you can add com.googlecode.utterlyidle.modules.PerformanceModule to your web application. PerformanceModule adds not only Gzip support, but also caching and Etag support. By default only Javascript and CSS files are gzipped.
If you want to have full control of Gzip support in your application, you can define Gzip policy and decorate HttpHandler with GzipHandler:
import com.googlecode.utterlyidle.HttpHandler;
import com.googlecode.utterlyidle.MediaType;
import com.googlecode.utterlyidle.handlers.GZipPolicy;
import com.googlecode.utterlyidle.handlers.GzipHandler;
import com.googlecode.yadic.Container;
public class MyGzipModule implements RequestScopedModule {
@Override
public Container addPerRequestObjects(Container container) throws Exception {
container.addInstance(GZipPolicy.class, gZipPolicy().
add(contentType(MediaType.TEXT_JAVASCRIPT)).
add(contentType(MediaType.TEXT_CSS)));
return container.decorate(HttpHandler.class, GzipHandler.class);
}
}