Skip to content

Instantly share code, notes, and snippets.

@bryaakov
Created September 25, 2019 20:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryaakov/da0df0b825c8370a46b7f058279dec45 to your computer and use it in GitHub Desktop.
Save bryaakov/da0df0b825c8370a46b7f058279dec45 to your computer and use it in GitHub Desktop.
package controllers
import akka.stream.scaladsl.Source
import akka.util.ByteString
import com.google.inject.{Inject, Singleton}
import play.api.mvc._
import play.api.http.HttpEntity
@Singleton
class HomeController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {
private val length = 100000000
private val payload = ByteString.fromArray(Array.fill(length)('1'))
// doesn't work for slow clients
def large1(): Action[AnyContent] = Action { implicit req =>
val entity = HttpEntity.Streamed(Source.single(payload), Some(length.toLong), Some("text/plain"))
Result(ResponseHeader(OK), entity)
}
// doesn't work for slow clients
def large2(): Action[AnyContent] = Action { implicit req =>
val entity = HttpEntity.Strict(payload, Some("text/plain"))
Result(ResponseHeader(OK), entity)
}
// works for both regualr and slow clients
def large3(): Action[AnyContent] = Action { implicit req =>
val one = ByteString("1")
val iteratorSource = Source.fromIterator(() => Iterator.range(0, length).map(_ => one))
val entity = HttpEntity.Streamed(iteratorSource, Some(length.toLong), Some("text/plain"))
Result(ResponseHeader(OK), entity)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment