在Akka HTTP中,可以使用path和pathPrefix指令来验证路径段。以下是一个示例解决方案:
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
object Main extends App {
  implicit val system = ActorSystem("my-system")
  implicit val materializer = ActorMaterializer()
  implicit val executionContext = system.dispatcher
  val route =
    pathPrefix("users") {
      path(IntNumber) { id =>
        complete(s"User with id $id")
      } ~
      path(Segment) { username =>
        complete(s"User with username $username")
      }
    }
  val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)
  println("Server online at http://localhost:8080/")
}
在这个示例中,我们定义了一个route,它包含一个路径前缀users,后跟一个整数路径段和一个字符串路径段。IntNumber会验证路径段是否为整数,Segment会将路径段解析为字符串。根据路径段的类型,我们返回不同的响应。
绑定和处理器绑定到localhost的8080端口。一旦服务器启动,它将打印一条消息。
您可以在浏览器或任何HTTP客户端中访问以下URL以测试此示例:
http://localhost:8080/users/123:将返回User with id 123http://localhost:8080/users/john:将返回User with username john