Last active
December 20, 2015 18:39
-
-
Save zuzkins/6177875 to your computer and use it in GitHub Desktop.
spray contentType filtering directive
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 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