使用 Akka Http 中的编组器发送包含 Json 内容的 http 响应

Sending an http response with Json content using marshallers in Akka Http

我想发送一个 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。

否定条件的方法to[HttpResponse]承担Future[HttpResponse]。同时正条件returnsHttpResponse

尝试类似的东西(我假设 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