Created
February 26, 2014 14:07
-
-
Save nrinaudo/9230004 to your computer and use it in GitHub Desktop.
Sample implementation of automated un-gzipping of client entity bodies.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that this assumes a default charset of UTF-8, which technically isn't spec compliant (should be ISO-8859-1).