Skip to content

Instantly share code, notes, and snippets.

@hamnis
Created February 13, 2015 11:40
Show Gist options
  • Save hamnis/65066659f9850ff88314 to your computer and use it in GitHub Desktop.
Save hamnis/65066659f9850ff88314 to your computer and use it in GitHub Desktop.
def string[T](req: HttpRequest[T])(implicit codec: Codec = Codec.UTF8) = {
loan(new InputStreamReader(req.inputStream, codec.charSet)) { reader =>
val writer = new java.io.StringWriter
val ca = new Array[Char](4096)
@scala.annotation.tailrec def read() {
val len = reader.read(ca)
if (len > 0) writer.write(ca, 0, len)
if (len >= 0) read
}
read()
writer.toString
}
}
def loan[A <: java.io.Closeable, B](c: => A)(f: (A) => B): B = {
val cached = c
try { f(cached)} finally { cached.close() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment