akkasprayhttp-methodspray-dsl

Spray Routing not matching HTTP Method correctly


I am using Spray Routing to try to match routes using different HTTP method but when I do a GET request it actually goes through DELETE, PUT and GET. I thought delete and put rejects all requests that are not HTTP DELETE or HTTP PUT.

This is my basic code:

path(Segment ~ Slash.?) { id =>
  delete {
    println("Hello from DELETE")
    //do stuff for delete
    complete("done for DELETE")
  } ~
  put {
    println("Hello from PUT")
    //do stuff for put
    complete("done for PUT")
  } ~
  get {
    println("Hello from GET")
    //do stuff for get
    complete("done for GET")
  }
}

If I trigger a GET request I can see the app printing:

Hello from DELETE
Hello from PUT
Hello from GET

Am I missing any return call or something?


Solution

  • No, your code is (almost) correct.

    The issue is that, in spray, the code that lives in a method matcher but does not live under an extraction (one of the directives "extracting" something, such as "parameters" or "segment") is executed all times.

    In your case, you correctly match the path extractor, but after that the route executes for all get put delete etc.

    The solution for this is to add the "dynamic" keyword right below your get/put etc. The downside is that you lose some performance.

    path(...) {
      get {
        dynamic {
          ...
        }
      }
    }
    

    Alternatively, you can reshuffle your code so that the method matcher is at the top level, and the path extractor under it

    get {
       path(...) {
         ...
       }
    }