akka-http:如何设置响应头

akka-http: How to set response headers

我的路线如下:

val route = {
    logRequestResult("user-service") {
      pathPrefix("user") {
        get {
          respondWithHeader(RawHeader("Content-Type", "application/json")) {
            parameters("firstName".?, "lastName".?).as(Name) { name =>
              findUserByName(name) match {
                case Left(users) => complete(users)
                case Right(error) => complete(error)
              }
            }
          }
        } ~
          (put & entity(as[User])) { user =>
            complete(Created -> s"Hello ${user.firstName} ${user.lastName}")
          } ~
          (post & entity(as[User])) { user =>
            complete(s"Hello ${user.firstName} ${user.lastName}")
          } ~
          (delete & path(Segment)) { userId =>
            complete(s"Hello $userId")
          }
      }
    }
  }

我的响应内容类型应始终为 application/json,因为我为 get 请求设置了它。但是,我在测试中得到的是 text/plain。如何在响应中正确设置内容类型?

附带说明一下,akka-http 文档是我见过的最没有价值的垃圾之一。几乎每个 link 示例代码都被破坏了,他们的解释只是说明了显而易见的事情。 Javadoc 没有代码示例,我在 Github 上找不到他们的代码库,所以从他们的单元测试中学习也是不可能的。

我发现 this 一个 post 上面写着 "In spray/akka-http some headers are treated specially"。显然,内容类型是其中之一,因此不能像我上面的代码那样设置。必须改为创建具有所需内容类型和响应正文的 HttpEntity。有了这些知识,当我如下更改 get 指令时,它起作用了。

import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.model.MediaTypes.`application/json`

get {
  parameters("firstName".?, "lastName".?).as(Name) { name =>
    findUserByName(name) match {
      case Left(users) => complete(users)
      case Right(error) => complete(error._1, HttpEntity(`application/json`, error._2))
    }
  }
}