How to match specific accept headers in a route?

守給你的承諾、 提交于 2019-12-05 17:58:12

I would do this way:

def acceptOnly(mr: MediaRange*): Directive0 =
  extract(_.request.headers).flatMap[HNil] {
    case headers if headers.contains(Accept(mr)) ⇒ pass
    case _                                       ⇒ reject(MalformedHeaderRejection("Accept", s"Only the following media types are supported: ${mr.mkString(", ")}"))
  } & cancelAllRejections(ofType[MalformedHeaderRejection])

Then just wrap your root:

path("") {
  get {
    acceptOnly(`application/json`) {
      session { creds ⇒
        complete(html.page(creds))
      }
    }
  }
}

And by the way the latest spray 1.2 nightly is 1.2-20130928 if you can, update it

theon

There is no pre-defined directive called accept directive. You can see the full list of available directives here.

However, you can use the headerValueByName directive to make a custom directive that does what you desire:

def accept(required: String) = headerValueByName("Accept").flatMap {
  case actual if actual.split(",").contains(required) => pass
  case _ => reject(MalformedHeaderRejection("Accept", "Accept must be equal to " + required))
}

Put this code in scope of your spray Route, then just use as you have shown in your question.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!