我正在创建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的新手,请多多指教!
1条答案
按热度按时间ecbunoof1#
我不是zio-http(也不是一般的zio)Maven,但以下代码对我有效: