Since Spray.io is defining content types at a low-level, how do I simply reference the content-type of the incoming request?
Here's a short example where an image is PUT.
put {
entity(as[Array[Byte]]) { data =>
complete{
val guid = Image.getGuid(id)
val fileExtension = // match a file extension to content-type here
val key = "%s-%s.%s" format (id, guid, fileExtension )
val o = new Image(key, contentType, data)
Image.store(o)
val m = Map("path" -> "/client/%s/img/%s.%s" format (id, guid, fileExtension))
HttpResponse(OK, generate(m))
}
}
}
Given the code above, what's an easy way to extract the content type? I can simply use that to pattern-match to an appropriate fileExtension
. Thanks for your help.
You can build your own directive to extract the content-type:
val contentType =
headerValuePF {
case `Content-Type`(ct) => ct
}
and then use it in your route:
put {
entity(as[Array[Byte]]) { data =>
contentType { ct => // ct is instance of spray.http.ContentType
// ...
}
}
}
Edit: If you are on the nightly builds, MediaTypes already contain file extensions so you could use the ones from there. On 1.1-M7 you have to provide your own mapping as you suggested.
I think you can use the headerValue
directive from HeaderDirectives
:
import spray.http.HttpHeaders._
headerValue(_ match {
case `Content-Type`(ct) => Some(ct)
case _ => None
}) { ct =>
// ct has type ContentType
// other routes here
}
This is for Spray 1.0/1.1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With