Extract the Spray.io Content-Type from request?
Asked Answered
R

2

5

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.

Ribbing answered 6/5, 2013 at 20:55 Comment(0)
M
7

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.

Muscadel answered 7/5, 2013 at 9:54 Comment(0)
V
3

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.

Volga answered 7/5, 2013 at 6:40 Comment(1)
Thanks! Looks like this is indeed the "built-in" way to extract a header. I will admit @jrudolph's solution is more usable though since it works similarly to other extractions within Spray.Ribbing

© 2022 - 2024 — McMap. All rights reserved.