Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
safeDecodeRequest workaround
import akka.http.javadsl.model.HttpEntities;
import akka.http.javadsl.model.HttpEntity;
import akka.http.javadsl.model.RequestEntity;
import akka.http.javadsl.server.Route;
import java.util.function.Supplier;
import static akka.http.javadsl.server.Directives.decodeRequest;
import static akka.http.javadsl.server.Directives.mapRequest;
import static akka.http.javadsl.server.Directives.withSizeLimit;
public class SafeDecodeRequestDirectives {
public static Route safeDecodeRequest(long maxBytes, Supplier<Route> inner) {
return
decodeRequest(() ->
mapRequest(req -> req.withEntity(chunkedWithLimit(req.entity())), () ->
withSizeLimit(maxBytes, inner)
)
);
}
private static RequestEntity chunkedWithLimit(RequestEntity entity) {
if (entity.isChunked())
return
HttpEntities.createChunked(
entity.getContentType(),
akka.http.scaladsl.model.HttpEntity.limitableByteSource(((HttpEntity.Chunked)entity).getDataBytes().asScala()).asJava()
);
else
return entity;
}
}
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.server.Directives.decodeRequest
import akka.http.scaladsl.server.Directives.mapRequest
import akka.http.scaladsl.server.Directives.withSizeLimit
object SafeDecodeRequestDirectives {
def safeDecodeRequest(maxBytes: Long): Directive0 =
decodeRequest & mapRequest(_.mapEntity {
// decodeRequest will create chunked entity when it decodes something. Add the missing limit support.
case c: HttpEntity.Chunked c.copy(chunks = HttpEntity.limitableChunkSource(c.chunks))
case e e
}) & withSizeLimit(maxBytes)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment