Skip to content

Instantly share code, notes, and snippets.

@nrinaudo
Created February 26, 2014 14:07
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 nrinaudo/9230004 to your computer and use it in GitHub Desktop.
Save nrinaudo/9230004 to your computer and use it in GitHub Desktop.
Sample implementation of automated un-gzipping of client entity bodies.
import unfiltered.request._
import unfiltered.response.BadRequest
import unfiltered.Cycle
import java.nio.charset.Charset
import scala.util.Try
object ContentEncoding extends ConnegHeader("Content-Encoding")
object Encodes {
trait Encoding {
def unapply[A](req: HttpRequest[A]) = req match {
case ContentEncoding(encs) => if(encs.exists(acceptable)) Some(req) else None
case _ => None
}
def acceptable(enc: String) = Encodes.acceptable(encoding)(enc)
def encoding: String
}
def acceptable(encA: String)(encB: String) = encA.equalsIgnoreCase(encB)
def encoding(enc: String) = new Encoding { val encoding = enc }
val GZip = encoding("gzip")
// val Chunked = encoding("chunked")
// val Identity = encoding("identity")
// val Compress = encoding("compress")
// val Deflate = encoding("deflate")
}
object GZip {
private class GzippedRequest[T](req: HttpRequest[T], val charset: Charset) extends DelegatingRequest(req) {
def this(req: HttpRequest[T]) = this(req, Charset.forName("UTF-8"))
override def inputStream = new java.util.zip.GZIPInputStream(super.inputStream)
override def reader = new java.io.InputStreamReader(inputStream, charset)
}
def apply[A, B](intent: Cycle.Intent[A, B]) = Cycle.Intent[A, B] {
case Encodes.GZip(req) => req match {
case Charset(charset) => Try {Charset.forName(charset)} map {c =>
Cycle.Intent.complete(intent)(new GzippedRequest(req, c))
} getOrElse BadRequest
case _ => Cycle.Intent.complete(intent)(new GzippedRequest(req))
}
case req => Cycle.Intent.complete(intent)(req)
}
}
@nrinaudo
Copy link
Author

Note that this assumes a default charset of UTF-8, which technically isn't spec compliant (should be ISO-8859-1).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment