Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match specific accept headers in a route?

Tags:

scala

spray

I want to create a route that matches only if the client sends a specific Accept header. I use Spray 1.2-20130822.

I'd like to get the route working:

def receive = runRoute {
    get {
      path("") {
        accept("application/json") {
           complete(...)
        }
      }
    }
  }

Here I found a spec using an accept() function, but I can't figure out what to import in my Spray-Handler to make it work as directive. Also, I did not find other doc on header directives but these stubs.

like image 974
rompetroll Avatar asked Mar 23 '23 05:03

rompetroll


1 Answers

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

like image 193
4lex1v Avatar answered Mar 31 '23 23:03

4lex1v