scalatra

Scalatra multiple routes for single action


Currently i am trying to refactor a API without breaking changes. trying to migrate it from something like host:port/foo/bar to host:port/barand im wondering if in Scalatra multiple routes are supported on a single action. I am trying it like:

get("/foo/bar", "/bar") {
 Ok(200) 
}

its returning with a empty response on either endpoint with a response code of 0 so i'm kind of puzzled. Is this supported in Scalatra?

I know in spring it'd look something like: https://stackoverflow.com/a/5517486/4682816 but i am curious if there is something in Scalatra


Solution

  • Scalatra supports multiple transformers for a action, but it means the action in called if all transformers are matched. This is used to add additional conditions to the routing.

    In your case, a request path can't match both "/foo/bar" and "/bar", so I guess the action is never called.

    You can do it instead as follows:

    get("/foo/bar"){
      bar()
    }
    
    get("/bar"){
      bar()
    }
    
    private def bar() = {
      Ok(200)
    }
    

    or you can use regular expression:

    get("^(/bar)|(/foo/bar)$".r){
      Ok(200)
    }