简体   繁体   中英

How do extract path without variables in Akka Http?

I wish to obtain path without variables, for example, having api/test/132/123 I would like to get api/test . What is the best way of doing it? Can I get this done by using path directives - pathPrefix ? So far I can image something like this, eg, pass variables and remove them from string.

class UriSpec extends WordSpecLike with Matchers with ScalatestRouteTest {

  "Uri" should {

    "remain without identifiers" in new Scope {
      Get("/api/test/132/123") ~> testRoute ~> check {
        status should be(OK)
        responseAs[String] should be("/api/test")
      }
    }
  }

  private trait Scope extends Directives {

    def testRoute: Route =
      path("api" / "test" / LongNumber / LongNumber) { (n1, n2) =>
        extractMatchedPath { path =>
          complete(OK -> path.toString.replace(s"/$n1", "").replace(s"/$n2", ""))
        }
      }
  }
}

Thank you for your help. Sorry, I didn't managed to figure out how to use existing directives, nor find existing solution.

Your idea to use pathPrefix was along the right lines. You can use that to deal with the base path and then have a separate level to deal with the variables, extracting out the current matched path in between:

      def testRoute: Route =
         pathPrefix("api" / "test") {
            extractMatchedPath { basePath =>
               path(LongNumber / LongNumber) { (n1, n2) =>
                  complete(OK -> basePath.toString)
               }
            }
         }

That means you then have the base path separated out without the need to remove the variable parts.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM