HTTP Client-Server Example
Client and Server Example
zio-http-example/src/main/scala/example/ClientServer.scala
package example
import zio.{Scope, ZIO, ZIOAppArgs, ZIOAppDefault}
import zio.http._
object ClientServer extends ZIOAppDefault {
private val url = URL.decode("http://localhost:8080/hello").toOption.get
private val app =
Routes(
Method.GET / "hello" -> handler(Response.text("hello")),
Method.GET / "" -> handler(ZClient.batched(Request.get(url))),
).sandbox
override val run: ZIO[Environment with ZIOAppArgs with Scope, Any, Any] =
Server.serve(app).provide(Server.default, Client.default)
}
Simple Client Example
zio-http-example/src/main/scala/example/SimpleClient.scala
package example
import zio._
import zio.http._
object SimpleClient extends ZIOAppDefault {
val url = URL.decode("https://jsonplaceholder.typicode.com/todos").toOption.get
val program = for {
client <- ZIO.service[Client]
res <- client.url(url).batched(Request.get("/"))
data <- res.body.asString
_ <- Console.printLine(data)
} yield ()
override val run = program.provide(Client.default)
}