1
votes

In some contexts I can match on the remaining path using a PathDirective to get the information I need about the path. For example, when route below is directly bound and handled by Akka HTTP, every request will echo back the requested path as desired.

val route =
  path(Remaining) { path =>
    complete(path)
  }

However, when the above route is combined elsewhere in the application, the path variable above may only hold part of the requested path not giving the desired results.

For example if the actual bound route is be,

val actualRoute = pathPrefix("echo") { route }

The "echo/" part of the overall path will be missing from the response given to the user.

How can the complete path be reliably accessed?

1

1 Answers

2
votes

Directives extractMatchedPath and extractUnmatchedPath let you access the path without matching the path like you path directive does above. These two can be combined to construct the full path:

val route =
  extractMatchedPath { matched =>
    extractUnmatchedPath { unmatched =>
      complete((matched.dropChars(1) ++ unmatched).toString)
    }
  }

However it is probably cleaner just to extract the Path from the URI directly:

val route =
  extractUri { uri =>
    complete(uri.toRelative.path.dropChars(1).toString)
  }

Note that in both cases we needed to call .dropChars(1) to drop the initial forward slash and be consistent with the output you got using the path directive.