akka-http:如何设置响应头 [英] akka-http: How to set response headers

查看:163
本文介绍了akka-http:如何设置响应头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的路线如下:

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 ,因为我已将其设置为获取请求。但是,我在测试中得到的是 text / plain 。如何在响应中正确设置内容类型?

The content type of my response should always be application/json as I've it set for the get request. However, what I'm getting in my tests is text/plain. How do I set the content type correctly in the response?

另一方面,akka-http文档是我所见过的最无用的垃圾之一看过。几乎所有与示例代码的链接都被打断了,它们的解释只是显而易见的。 Javadoc没有代码示例,我无法在Github上找到他们的代码库,因此从他们的单元测试中学习也是不可能的。

On a side note, the akka-http documentation is one of the most worthless piece of garbage I've ever seen. Almost every link to example code is broken and their explanations merely state the obvious. Javadoc has no code example and I couldn't find their codebase on Github so learning from their unit tests is also out of the question.

推荐答案

我找到了 一个 >帖子,上面写着在spray / akka-http中,某些标题被特殊地。显然,内容类型是其中之一,因此无法按照我上面的代码进行设置。而是必须使用所需的内容类型和响应主体创建一个 HttpEntity 。有了这些知识,当我如下更改 get 指令时,它就起作用了。

I found this one post that says "In spray/akka-http some headers are treated specially". Apparently, content type is one of those and hence can't be set as in my code above. One has to instead create an HttpEntity with the desired content type and response body. With that knowledge, when I changed the get directive as follows, it worked.

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))
    }
  }
}

这篇关于akka-http:如何设置响应头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆