decodeRequest

Signature

def decodeRequest: Directive0 

Description

Decompresses the incoming request if it is gzip or deflate compressed. Uncompressed requests are passed through untouched. If the request encoded with another encoding the request is rejected with an UnsupportedRequestEncodingRejectionUnsupportedRequestEncodingRejection. If the request entity after decoding exceeds pekko.http.routing.decode-max-size the stream fails with an EntityStreamSizeExceptionEntityStreamSizeException.

Example

Scala
sourceval route =
  decodeRequest {
    entity(as[String]) { (content: String) =>
      complete(s"Request content: '$content'")
    }
  }

// tests:
Post("/", helloGzipped) ~> `Content-Encoding`(gzip) ~> route ~> check {
  responseAs[String] shouldEqual "Request content: 'Hello'"
}
Post("/", helloDeflated) ~> `Content-Encoding`(deflate) ~> route ~> check {
  responseAs[String] shouldEqual "Request content: 'Hello'"
}
Post("/", "hello uncompressed") ~> `Content-Encoding`(identity) ~> route ~> check {
  responseAs[String] shouldEqual "Request content: 'hello uncompressed'"
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.decodeRequest;
import static org.apache.pekko.http.javadsl.server.Directives.entity;

final ByteString helloGzipped = Coder.Gzip.encode(ByteString.fromString("Hello"));
final ByteString helloDeflated = Coder.Deflate.encode(ByteString.fromString("Hello"));

final Route route =
    decodeRequest(
        () ->
            entity(
                entityToString(), content -> complete("Request content: '" + content + "'")));

// tests:
testRoute(route)
    .run(
        HttpRequest.POST("/")
            .withEntity(helloGzipped)
            .addHeader(ContentEncoding.create(HttpEncodings.GZIP)))
    .assertEntity("Request content: 'Hello'");

testRoute(route)
    .run(
        HttpRequest.POST("/")
            .withEntity(helloDeflated)
            .addHeader(ContentEncoding.create(HttpEncodings.DEFLATE)))
    .assertEntity("Request content: 'Hello'");

testRoute(route)
    .run(
        HttpRequest.POST("/")
            .withEntity("hello uncompressed")
            .addHeader(ContentEncoding.create(HttpEncodings.IDENTITY)))
    .assertEntity("Request content: 'hello uncompressed'");