Skip to content

Instantly share code, notes, and snippets.

@mpkocher
Forked from joseraya/CorsSupport.scala
Last active August 29, 2015 14:20
Show Gist options
  • Save mpkocher/72a2b29ebce4b681052c to your computer and use it in GitHub Desktop.
Save mpkocher/72a2b29ebce4b681052c to your computer and use it in GitHub Desktop.
import spray.http.HttpMethods._
import spray.http.{HttpResponse, HttpMethod, HttpMethods, AllOrigins}
import spray.http.HttpHeaders.{`Access-Control-Allow-Methods`, `Access-Control-Max-Age`, `Access-Control-Allow-Headers`, `Access-Control-Allow-Origin`}
import spray.routing._
import spray.routing.directives.BasicDirectives
/**
* Forked from
*
* https://gist.github.com/joseraya/176821d856b43b1cfe19
*
* See Also
* https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
* http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server
*/
trait CORSSupport extends BasicDirectives{
private val allowOriginHeader = `Access-Control-Allow-Origin`(AllOrigins)
private val optionsCorsHeaders = List(
`Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Accept-Encoding, Accept-Language, Host, Referer, User-Agent"),
`Access-Control-Max-Age`(1728000))
def cors[T]: Directive0 = mapRequestContext { ctx => ctx.withRouteResponseHandling({
//It is an option requeset for a resource that responds to some other method
case Rejected(x) if ctx.request.method.equals(HttpMethods.OPTIONS) && !x.filter(_.isInstanceOf[MethodRejection]).isEmpty =>
val allowedMethods: List[HttpMethod] = x.filter(_.isInstanceOf[MethodRejection]).map(rejection => {
rejection.asInstanceOf[MethodRejection].supported
})
ctx.complete(HttpResponse().withHeaders(
`Access-Control-Allow-Methods`(OPTIONS, allowedMethods: _*) :: allowOriginHeader ::
optionsCorsHeaders
))
}).withHttpResponseHeadersMapped { headers =>
allowOriginHeader :: headers
}
}
}
val routes: Route =
cors {
path("hello") {
get {
complete {
"GET"
}
} ~
put {
complete {
"PUT"
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment