如何指定 Spray Content-Type 响应标头?

2023-11-22

我知道喷雾为我做到了这一点,但我仍然想用我的标头覆盖它,如何覆盖响应中的标头?

我的回复如下:

case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
  sender ! HttpResponse(entity = """{ "key": "value" }""" // here i want to specify also response header i would like to explicitly set it and not get it implicitly

如果您仍然想使用喷雾罐,那么您有两个选择,基于 HttpResponse 是一个案例类。第一个是传递一个具有显式内容类型的列表:

import spray.http.HttpHeaders._
import spray.http.ContentTypes._

def receive = {
    case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
      sender ! HttpResponse(entity = """{ "key": "value" }""", headers = List(`Content-Type`(`application/json`)))
  }

或者,第二种方法是使用方法withHeaders method:

def receive = {
    case HttpRequest(GET, Uri.Path("/something"), _, _, _) =>
      val response: HttpResponse = HttpResponse(entity = """{ "key": "value" }""")
      sender ! response.withHeaders(List(`Content-Type`(`application/json`)))
  }

但仍然像jrudolph据说,使用喷射路由要好得多,在这种情况下看起来会更好:

def receive = runRoute {
    path("/something") {
      get {
        respondWithHeader(`Content-Type`(`application/json`)) {
          complete("""{ "key": "value" }""")
        }
      }
    }
  }

但 Spray 让它变得更加容易,并为您处理所有(取消)编组:

import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

def receive = runRoute {
  (path("/something") & get) {
    complete(Map("key" -> "value"))
  }
}

在这种情况下,响应类型将设置为application/json通过喷雾本身。

我的评论的完整示例:

class FullProfileServiceStack
  extends HttpServiceActor
     with ProfileServiceStack
     with ... {
  def actorRefFactory = context
  def receive = runRoute(serviceRoutes)
}

object Launcher extends App {
  import Settings.service._
  implicit val system = ActorSystem("Profile-Service")
  import system.log

  log.info("Starting service actor")
  val handler = system.actorOf(Props[FullProfileServiceStack], "ProfileActor")

  log.info("Starting Http connection")
  IO(Http) ! Http.Bind(handler, interface = host, port = port)
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何指定 Spray Content-Type 响应标头? 的相关文章

随机推荐