【问题标题】:Get http headers with akka routing dsl使用 akka 路由 dsl 获取 http 标头
【发布时间】:2016-09-20 20:48:15
【问题描述】:

我是 Scala 新手,这个问题让我很沮丧。如何从请求中获取所有标头?

val route =  {
  path("lol") {
    //get httpHeaders
    complete(HttpResponse())
  }
}

【问题讨论】:

    标签: scala akka akka-http


    【解决方案1】:

    您至少有两个选择:

    a) 使用extractRequest 指令:

    val route = {
      path("example") {
        extractRequest { request =>
          request.headers // Returns `Seq[HttpHeader]`; do anything you want here
          complete(HttpResponse())
        }
      }
    }
    

    b) 显式访问RequestContext

    val route =  {
      path("example") { ctx =>
        ctx.request.headers // Returns `Seq[HttpHeader]`; do anything you want here
        ctx.complete(...)
      }
    }
    

    还有一系列与标头相关的指令,例如headerValueByNameoptionalHeaderValueByName。你可以找到详情here

    【讨论】:

    • extractRequest 指令可能是无需手动定义路由即可获取标头的最直接方法。
    • @RüdigerKlaehn:谢谢!我已经扩展了我的答案;)
    • 恕我直言,应该有path() { get { ctx => } } 来编译
    • 为什么是 Seq 而不是 Map?
    猜你喜欢
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多