首页 > 解决方案 > Akka HTTP 路由处理

问题描述

我有以下路线设置

 val routes = protectedRoute("wallet") { user =>
    concat {
      path("wallet" / "deposit") {
        get {
          completeEitherT(walletService.deposit(user._id, "dollars", 50))
        }
      }
      path("wallet") {
        get {
          completeEitherT(walletService.getForUser(user._id))
        }
      }
    }
  }

功能completeEitherT如下

def completeEitherT[T](t: EitherT[Future, DatabaseError, T])(implicit marsh: ToResponseMarshaller[T]): Route = {
    onSuccess(t.value) {
      case Left(x: DatabaseErrors.NotFound) =>
        logger.error(x.toString)
        complete(StatusCodes.NotFound)
      case Left(error) => complete(StatusCodes.InternalServerError)
      case Right(value) => complete(value)
    }
  }

protectedRoute指令是:

def protectedRoute(permissions: String*): Directive1[User] = new Directive1[User] {
    override def tapply(f: (Tuple1[User]) => Route): Route = {
      headerValueByName("Authorization") { jwt =>
        Jwt.decode(jwt, jwtSecret, List(algo)) match {
          case Failure(_) =>
            logger.error("Unauthorized access from jwtToken:", jwt)
            complete(StatusCodes.Unauthorized)
          case Success(value) =>
            val user = JsonParser(value.content).convertTo[User]
            if (user.roles.flatMap(_.permissions).exists(permissions.contains)) f(Tuple1(user))
            else complete(StatusCodes.Forbidden)
        }
      }
    }
  }

我遇到的问题是,当通过 Postman 调用时,首先定义的任何路径都会导致 404。

The requested resource could not be found.

这不是响应,completeEitherT因为它没有记录错误

如何在同一指令中定义两个或多个路径?

标签: scalajwtakkaakka-httpscala-cats

解决方案


请标记为重复,我在 Google 搜索中找不到此内容,但 SO 将其显示为相关。

回答

本质上我~在路径之间缺少一个

val routes = protectedRoute("wallet") { user =>
    concat {
      path("wallet" / "deposit") {
        get {
          completeEitherT(walletService.deposit(user._id, "dollars", 50))
        }
      } ~
      path("wallet") {
        get {
          completeEitherT(walletService.getForUser(user._id))
        }
      }
    }
  }

推荐阅读