scala ZioHttp终结点-返回json响应

xoshrz7s  于 2022-11-09  发布在  Scala
关注(0)|答案(1)|浏览(162)

我正在创建ZioHttp REST终结点...
对于Json请求,我想返回Json响应...
我可以返回日志,打印行,但不确定如何返回json响应...
以下是我的代码:

import zio.{Console, _}
import zhttp._
import zhttp.http._
import zhttp.service.Server
import zio.json.{DeriveJsonEncoder, JsonEncoder}

//import java.io.Console

object ZioHttp extends ZIOAppDefault {

  val port = 9000

  val app: Http[Any, Nothing, Request, Response] = Http.collect[Request] {
    case Method.GET -> !! / "zioCollector" => Response.text("Hello, Http server This is Mohammed Mukhtar Ali!!")
  }

  case class Events(experimentId: String,
                    variantId: String,
                    accountId: String,
                    deviceId: String,
                    date: Int)

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

  val zApp: UHttpApp = Http.collectZIO[Request] {
    case Method.POST -> !! / "zioCollector" =>
      Random.nextIntBetween(3, 5).map(n => Response.text("Hello " * n + "server2!"))
  }

  //  val zApp2: UHttpApp = Http.collectZIO[Request] {
  //    case Method.POST -> !! / "zioCollector" =>
  //      Random.nextIntBetween(3, 5).map(n => Response.json()
  //  }

  val combied = app ++ zApp

  val httpProgram = for {
    _ <- Console.printLine(s"Starting server at http://localhost:$port")
    _ <- Server.start(port, combied)
  } yield ()

  override def run = httpProgram

}

我是Zio和Scala的新手,请多多指教!

ecbunoof

ecbunoof1#

我不是zio-http(也不是一般的zio)Maven,但以下代码对我有效:

import zhttp.*
import zhttp.http.*
import zhttp.service.Server
import zio.json.*
import zio.Console
import zio.*

object ZioHttp extends ZIOAppDefault {

  val port = 9000

  case class Events(
    experimentId: String,
    variantId: String,
    accountId: String,
    deviceId: String,
    date: Int
  )

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

  val exampleEvents =
    Events(
      "someExperimentId",
      "someVariantId",
      "someAccountId",
      "someDeviceId",
      42
    )

  val zApp: UHttpApp = Http.collectZIO[Request] {
    case Method.GET -> !! / "exampleEvents" =>
      ZIO.succeed(Response.json(exampleEvents.toJson))
  }

  val httpProgram = for {
    _ <- Console.printLine(s"Starting server at http://localhost:$port")
    _ <- Server.start(port, zApp)
  } yield ()

  override def run = httpProgram

}

相关问题