ZioHttp端点-返回json响应



我正在创建一个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的初学者,感谢提供的任何帮助!

不是zio-http的专家(也不是一般的zio(,但这段代码对我有效:

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
}

相关内容

  • 没有找到相关文章

最新更新