简体   繁体   English

Scala,ZIO - 如何在 zio-http 中返回自定义响应?

[英]Scala, ZIO - how to return custom response in zio-http?

do you know how I can return custom object as zio-http response?你知道我如何将自定义 object 作为zio-http响应返回吗? I created simple class:我创建了简单的 class:

final case class CustomerResponse(id: Int, name: String, age: Int)

object CustomerResponse {
      implicit val responseCodec: Codec[CustomerResponse] = deriveCodec[CustomerResponse]
    }

and now I would like to return this CustomerResponse as Http response object:现在我想将此 CustomerResponse 作为 Http 响应 object 返回:

Http.collect[Request] { case Method.GET -> !! / "customer" => // Response.as CustomerResponse

I tried to use我试着用

Response.json(CustomerResponse(1, "a", 1))

but it didnt work.但它没有用。 Do you know how should I do it?你知道我该怎么做吗?

Great question.好问题。

I think you can use ZIO Json to accomplish this.我认为您可以使用 ZIO Json 来完成此操作。 I am using ZIO 2 which seems to mess some things up however我正在使用 ZIO 2 这似乎把一些事情搞砸了

case class CustomerResponse(id: Int, name: String, age: Int)

object CustomerResponse {
  implicit val encoder: JsonEncoder[CustomerResponse] = DeriveJsonEncoder.gen[CustomerResponse]
}

object CustomerServer extends ZIOAppDefault {
  val app: HttpApp[Any, Nothing] = Http.collect[Request] {
    case Method.GET -> !! / "customer" => Response.text(CustomerResponse(1, "w33b", 99).toJson)

  }

  override val run = Server.start(8090, app)


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM