在Akka Http中使用marshallers发送带有Json内容的http响应

时间:2017-06-04 18:10:57

标签: json scala marshalling akka-http argonaut

我想发送一个Http错误响应,并在主体中发送JSON格式的消息。我无法使用PredefinedToResponseMarshallers

我在Akka docs中看到了一个实现,但我尝试了类似的事情,它会引发编译错误。

import argonaut._, Argonaut._
import akka.http.scaladsl.marshalling.Marshal
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.marshalling.{ Marshaller, ToResponseMarshaller } 

trait Sample extends Marshallers with Directives { 
     def login(user: Login): CRIX[HttpResponse] = {
        for {
          verification ← verify(user)
          resp = if (verification) {
            HttpResponse(NoContent, headers = Seq(
              .........
            ))
          }//below is my http Error response
          else Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse]
        } yield resp
      }
    }

它给出了这个编译错误:

Sample.scala:164: type mismatch;
[error]  found   : Object
[error]  required: akka.http.scaladsl.model.HttpResponse
[error]     } yield resp
[error]             ^
[error] one error found
[error] (http/compile:compileIncremental) Compilation failed

我刚刚开始Akka Http,请原谅我,如果这很容易。

TL; DR:我想(例子)学习如何在Akka Http中使用ToResponseMarshallers。

1 个答案:

答案 0 :(得分:1)

负面条件的方法to[HttpResponse]采用Future[HttpResponse]。同时积极条件返回HttpResponse

尝试类似的事情(我假设verify接受Future[T]):

for {
  verification <- verify(user)
  resp <- if (verification) 
           Future.successful(HttpResponse(NoContent, headers = Seq(.........)) )
         else 
           Marshal(401 → "It is an Unauthorized Request".asJson).to[HttpResponse]
} yield resp