Skip to content

Instantly share code, notes, and snippets.

@samuelorji
Last active May 3, 2020 15:42
Show Gist options
  • Save samuelorji/b6b7403669961a8a0031f25e03294293 to your computer and use it in GitHub Desktop.
Save samuelorji/b6b7403669961a8a0031f25e03294293 to your computer and use it in GitHub Desktop.
Stream correct
val route = path("download") {
get {
optionalHeaderValueByName("Range") {
case None =>
// there must always be range header
complete(StatusCodes.RequestedRangeNotSatisfiable)
case Some(range) =>
val file = new File("movie.mp4")
val fileSize = file.length()
//Range header is usually Range: bytes=12943360-
val rng = range.split("=")(1).split("-")
val start = rng(0).toInt
//most of the time, there is no end range, just a start, in that case,
//we use the file size as the end range.
val end = if (rng.length > 1) {
//there is end range
rng(1).toLong
} else {
fileSize - 1
}
respondWithHeaders(List(
RawHeader("Content-Range", s"bytes ${start}-${end}/${fileSize}"),
RawHeader("Accept-Ranges", s"bytes")
)) {
complete(HttpResponse(StatusCodes.PartialContent, entity = HttpEntity(MediaTypes.`video/mp4`,
FileIO.fromPath(file.toPath, 8192, start.toInt))))
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment