Skip to content

Instantly share code, notes, and snippets.

@zuzkins
Last active December 20, 2015 18:39
Show Gist options
  • Save zuzkins/6177875 to your computer and use it in GitHub Desktop.
Save zuzkins/6177875 to your computer and use it in GitHub Desktop.
spray contentType filtering directive
import spray.http._
import shapeless.HNil
import spray.util.pimpSeq
def withContentType(ctStr: String): Directive0 = {
def isContentType(h: HttpHeader) = h match {
case HttpHeaders.`Content-Type`(ContentType(MediaType(mt), _)) ⇒ Some(mt)
case _ ⇒ None
}
extract(_.request.headers.mapFind(isContentType(_))).flatMap[HNil] {
case Some(curr) if curr == ctStr ⇒ pass
case x ⇒ reject(ContentTypeRejection(ctStr))
} & cancelAllRejections(ofType[ContentTypeRejection])
}
case class ContentTypeRejection(ctype: String) extends Rejection
/**
* usage example:
path("") {
authUser { user ⇒
post {
parameters((
'fileType.as[String],
'fileName.as[String]?
)) { (fileType: String, fileName: Option[String]) ⇒
withContentType("application/octet-stream") {
import eu.be3d.api.marshaller.OctetStreamUnmarshaller.OctetStreamUnmarshaller
entity(as[Array[Byte]]) { bytes ⇒
doSomethingWith(bytes)
}
} ~
withContentType("application/x-data-url") {
import eu.be3d.api.marshaller.DataUrlUnmarshallers.DataUrlUnmarshaller
entity(as[DataUrlFile]) { contents ⇒
doSomethingWith(contents)
}
}
}
}
}
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment