EncodingDirectives

When to use which compression directive?

There are three different directives for performing response compressing with slightly different behavior:

encodeResponse
Always compresses the response with the one given encoding, rejects the request with an UnacceptedResponseEncodingRejection if the client doesn’t accept the given encoding. The other compression directives are built upon this one. See its description for an overview how they relate exactly.
compressResponse
Uses the first of a given number of encodings that the client accepts. If none are accepted the request is rejected.
compressResponseIfRequested
Only compresses the response when specifically requested by the Accept-Encoding request header (i.e. the default is “no compression”).

See the individual directives for more detailed usage examples.

When to use which decompression directive?

There are two different directives for performing request decompressing with slightly different behavior:

decodeRequest
Attempts to decompress the request using the one given decoder, rejects the request with an UnsupportedRequestEncodingRejection if the request is not encoded with the given encoder.
decompressRequest
Decompresses the request if it is encoded with one of the given encoders. If the request’s encoding doesn’t match one of the given encoders it is rejected.

Combining compression and decompression

As with all Spray directives, the above single directives can be combined using & to produce compound directives that will decompress requests and compress responses in whatever combination required. Some examples:

"the (decompressRequest & compressResponse) compound directive" should {
  val decompressCompress = (decompressRequest() & compressResponse())
  "decompress a GZIP compressed request and produce a GZIP compressed response if the request has no Accept-Encoding header" in {
    Get("/", helloGzipped) ~> `Content-Encoding`(gzip) ~> {
      decompressCompress { echoRequestContent }
    } ~> check {
      response must haveContentEncoding(gzip)
      body === HttpEntity(ContentType(`text/plain`, `UTF-8`), helloGzipped)
    }
  }
  "decompress a GZIP compressed request and produce a Deflate compressed response if the request has an `Accept-Encoding: deflate` header" in {
    Get("/", helloGzipped) ~> `Content-Encoding`(gzip) ~> `Accept-Encoding`(deflate) ~> {
      decompressCompress { echoRequestContent }
    } ~> check {
      response must haveContentEncoding(deflate)
      body === HttpEntity(ContentType(`text/plain`, `UTF-8`), helloDeflated)
    }
  }
  "decompress an uncompressed request and produce a GZIP compressed response if the request has an `Accept-Encoding: gzip` header" in {
    Get("/", "Hello") ~> `Accept-Encoding`(gzip) ~> {
      decompressCompress { echoRequestContent }
    } ~> check {
      response must haveContentEncoding(gzip)
      body === HttpEntity(ContentType(`text/plain`, `UTF-8`), helloGzipped)
    }
  }
}