withPrecompressedMediaTypeSupport

Signature

def withPrecompressedMediaTypeSupport: Directive0

Description

Inspects the response entity and adds a Content-Encoding: gzip response header if the entity’s media-type is precompressed with gzip and no Content-Encoding header is present yet.

Example

Scala
val svgz = compress("<svg/>", Coders.Gzip)
val route =
  withPrecompressedMediaTypeSupport {
    complete(HttpResponse(entity = HttpEntity(`image/svgz`, svgz)))
  }

// tests:
Get("/") ~> route ~> check {
  header[`Content-Encoding`] shouldEqual Some(`Content-Encoding`(gzip))
  mediaType shouldEqual `image/svg+xml`
}
Java
import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.withPrecompressedMediaTypeSupport;

final ByteString svgz = Coder.Gzip.encode(ByteString.fromString("<svg/>"));

final Route route = withPrecompressedMediaTypeSupport(() ->
  complete(
    HttpResponse.create().withEntity(
      HttpEntities.create(MediaTypes.IMAGE_SVGZ.toContentType(), svgz))
  )
);

// tests:
testRoute(route).run(HttpRequest.GET("/"))
  .assertMediaType(MediaTypes.IMAGE_SVG_XML)
  .assertHeaderExists(ContentEncoding.create(HttpEncodings.GZIP));
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.