それでもスプレー缶を使用したい場合は、HttpResponse がケース クラスであることから、2 つのオプションがあります。1 つ目は、明示的なコンテンツ タイプを持つ List を渡すことです。
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`)))
}
または、2 番目の方法は、メソッドwithHeaders
メソッドを使用することです。
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" }""")
}
}
}
}
しかし、スプレーを使用するとさらに簡単になり、すべての (非) マーシャリングを処理できます。
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)
}