decodeRequestWith

Signature

def decodeRequestWith(decoder: Decoder): Directive0
def decodeRequestWith(decoders: Decoder*): Directive0

Description

Decodes the incoming request if it is encoded with one of the given encoders. If the request encoding doesn’t match one of the given encoders the request is rejected with an UnsupportedRequestEncodingRejection. If no decoders are given the default encoders (Gzip, Deflate, NoCoding) are used.

Example

val route =
  decodeRequestWith(Gzip) {
    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 {
  rejection shouldEqual UnsupportedRequestEncodingRejection(gzip)
}
Post("/", "hello") ~> `Content-Encoding`(identity) ~> route ~> check {
  rejection shouldEqual UnsupportedRequestEncodingRejection(gzip)
}
val route =
  decodeRequestWith(Gzip, NoCoding) {
    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 {
  rejections shouldEqual List(UnsupportedRequestEncodingRejection(gzip), UnsupportedRequestEncodingRejection(identity))
}
Post("/", "hello uncompressed") ~> `Content-Encoding`(identity) ~> route ~> check {
  responseAs[String] shouldEqual "Request content: 'hello uncompressed'"
}
The source code for this page can be found here.