2013-05-06 46 views
5

由于Spray.io正在定义低级别的内容类型,我如何简单地引用传入请求的内容类型?从请求中提取Spray.io内容类型?

下面是一个简短的例子,图像是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)) 
      } 
     } 
     } 

鉴于上面的代码,提取内容类型的简单方法是什么?我可以简单地使用它来模式匹配到合适的fileExtension。谢谢你的帮助。

回答

7

你可以建立自己的指令提取内容类型:

val contentType = headerValuePF { case `Content-Type`(ct) => ct }

,然后在您的路线使用它:

put { 
    entity(as[Array[Byte]]) { data => 
     contentType { ct => // ct is instance of spray.http.ContentType 
     // ... 
     } 
    } 
    } 

编辑:如果您在每晚构建,MediaTypes已经包含文件扩展名,所以你可以使用那里的文件扩展名。在1.1-M7上,您必须按照您的建议提供您自己的映射。

3

我想你可以使用headerValue指令从HeaderDirectives

import spray.http.HttpHeaders._ 
headerValue(_ match { 
    case `Content-Type`(ct) => Some(ct) 
    case _ => None 
}) { ct => 
    // ct has type ContentType 
    // other routes here 
} 

这是喷雾1.0/1.1。

+0

谢谢!看起来这确实是提取标题的“内置”方法。我会承认@ jrudolph的解决方案更加实用,虽然它与Spray中的其他提取类似。 – crockpotveggies 2013-05-07 16:44:18