Akka-http:如何从请求中获取自定义 header?

Akka-http: How to get custom header from a request?

我向 akka-http api 发送以下 header 请求:"Content-type": "application/json""Accept": "application/json""AppId": "some_id"

如何在我的 akka-http 路线中获得 "AppId" 自定义 header?

(get & parameters("id")) { (id) =>
      complete {
        val appId = ?? // I want to get custom header here.
      }
    } 

谢谢。

您需要使用 HeaderDirectivesHeaderDirectives docs) to extract the header. For example, if it's a custom one you can use headerValueByName 之一,它产生 header 的值,如果 header 不存在则拒绝路由(如果 header 是可选的,您可以使用 optionalHeaderValueByName):

headerValueByName("AppId") { appId =>
  complete(s"The AppId was: $appId")
}

Hakking 快乐!

我实际上更喜欢为身份验证令牌、应用程序 ID 和其他服务客户请求所必需的参数创建自定义指令。在你的情况下,它可能看起来像这样

val extractAppId = (headerValueByName("AppId") | headerValueByName("AppId2")).tflatMap[Tuple1[String]] {
  case Tuple1(appId) =>
    if (!appId.equalsIgnoreCase("BannedAppId"))
      provide(appId)
    else
      complete(StatusCodes.Forbidden -> "Your application is banned")
}.recover {
  case rejections => reject(ValidationRejection("AppId is not provided"))
}

一样使用
extractAppId { appId =>
 get {
  complete {
   "Your AppId is " + appId
  }
 }
}

为了让我的示例更有趣,我添加了对基于提供的 AppId 的条件响应的支持。