Alex Fruzenshtein
Alex Fruzenshtein

Reputation: 3126

Akka Http retrieve a string value with help of Segment PathMatcher

I'm trying to implement a simple API where I can get path parameter as a String. Here is my test code:

class SimpleRouteTest extends WordSpec
  with Matchers
  with ScalatestRouteTest {

  val routes: Route = pathPrefix("foo") {
    get {
      complete("GET /foo")
    } ~
    pathPrefix(Segment) { seg =>
      get {
        complete(s"GET /foo/$seg")
      }
    }
  }

  "The routes should handle" should {
    "GET /foo correctly" in {
      Get("/foo") ~> routes ~> check {
        responseAs[String] shouldBe  "GET /foo"
      }
    }
    "GET /foo/any" in {
      Get("/foo/any") ~> routes ~> check {
        responseAs[String] shouldBe  "GET /foo/any"
      }
    }
  }

}

Unfortunately the second test fails with message:

"GET /foo[]" was not equal to "GET /foo[/any]"

Who can give a hint, what I'm doing wrong?

Thanks

Upvotes: 0

Views: 1018

Answers (1)

Cyrille Corpet
Cyrille Corpet

Reputation: 5315

This is what your code tries to do:

  • match the path with the prefix /foo
  • if method is GET, complete with "GET /foo"
  • otherwise if the remaining path starts with some segment seg, complete with s"GET /foo/$seg"

The ~ operator stops at the first operand, since all the condition are met (starts with /foo and is a GET). You might want to pass the more precise one as first operand, or specify that you want a PathEnd in your first case.

Upvotes: 2

Related Questions