Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract the Spray.io Content-Type from request?

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.

like image 692
crockpotveggies Avatar asked May 06 '13 20:05

crockpotveggies


2 Answers

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.

like image 94
jrudolph Avatar answered Oct 26 '22 19:10

jrudolph


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.

like image 28
adamw Avatar answered Oct 26 '22 19:10

adamw