【问题标题】:Sending an http response with Json content using marshallers in Akka Http使用 Akka Http 中的编组器发送带有 Json 内容的 http 响应
【发布时间】:2017-06-04 18:10:56
【问题描述】:

我想在正文中发送带有 JSON 格式消息的 Http 错误响应。我在使用 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。

【问题讨论】:

    标签: json scala marshalling akka-http argonaut


    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-14
      • 2016-01-12
      • 2017-02-06
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多