toStrictEntity
Signature
def toStrictEntity(timeout: FiniteDuration): Directive0
def toStrictEntity(timeout: FiniteDuration, maxBytes: Long): Directive0
Description
Transforms the request entity to strict entity before it is handled by the inner route.
A timeout parameter is given and if the stream isn’t completed after the timeout, the directive will be failed.
Warning
The directive will read the request entity into memory within the size limit(8M by default) and effectively disable streaming. The size limit can be configured globally with pekko.http.parsing.max-content-length
or overridden by wrapping with withSizeLimit or withoutSizeLimit directive.
Example
- Scala
-
source
import scala.concurrent.duration._ val route = toStrictEntity(3.seconds) { extractRequest { req => req.entity match { case strict: HttpEntity.Strict => complete(s"Request entity is strict, data=${strict.data.utf8String}") case _ => complete("Ooops, request entity is not strict!") } } } // tests: val dataBytes = Source.fromIterator(() => Iterator.range(1, 10).map(x => ByteString(x.toString))) Post("/", HttpEntity(ContentTypes.`text/plain(UTF-8)`, data = dataBytes)) ~> route ~> check { responseAs[String] shouldEqual "Request entity is strict, data=123456789" }
- Java
-
source
import static org.apache.pekko.http.javadsl.server.Directives.toStrictEntity; final FiniteDuration timeout = FiniteDuration.create(3, TimeUnit.SECONDS); final Route route = toStrictEntity( timeout, () -> extractRequest( req -> { if (req.entity() instanceof HttpEntity.Strict) { final HttpEntity.Strict strict = (HttpEntity.Strict) req.entity(); return complete( "Request entity is strict, data=" + strict.getData().utf8String()); } else { return complete("Ooops, request entity is not strict!"); } })); // tests: final Iterator iterator = Arrays.asList( ByteString.fromString("1"), ByteString.fromString("2"), ByteString.fromString("3")) .iterator(); final Source<ByteString, NotUsed> dataBytes = Source.fromIterator(() -> iterator); testRoute(route) .run( HttpRequest.POST("/") .withEntity(HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8, dataBytes))) .assertEntity("Request entity is strict, data=123");
1.1.0