extractDataBytes
Description
Extracts the entities data bytes as Source<ByteString, ?>
Source[ByteString, _]
from the RequestContext
RequestContext
.
The directive returns a stream containing the request data bytes.
Example
- Scala
-
source
val route = extractDataBytes { data => val sum = data.runFold(0) { (acc, i) => acc + i.utf8String.toInt } onSuccess(sum) { s => complete(HttpResponse(entity = HttpEntity(s.toString))) } } // tests: val dataBytes = Source.fromIterator(() => Iterator.range(1, 10).map(x => ByteString(x.toString))) Post("/abc", HttpEntity(ContentTypes.`text/plain(UTF-8)`, data = dataBytes)) ~> route ~> check { responseAs[String] shouldEqual "45" }
- Java
-
source
import static akka.http.javadsl.server.Directives.extractDataBytes; final Route route = extractDataBytes(data -> { final CompletionStage<Integer> sum = data.runFold(0, (acc, i) -> acc + Integer.valueOf(i.utf8String()), materializer()); return onSuccess(sum, s -> complete(HttpResponse.create().withEntity(HttpEntities.create(s.toString())))); }); // tests: final Iterator<ByteString> 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("abc") .withEntity(HttpEntities.create(ContentTypes.TEXT_PLAIN_UTF8, dataBytes)) ).assertEntity("6");