import zio.http._
import zio.http.service._
import zio.http.service.ServerChannelFactory
import zio._
import scala.util.Try
object HelloWorldAdvanced extends App {
private val PORT = 0
private val fooBar: HttpApp[Any, Nothing] = Http.collect[Request] {
case Method.GET -> !! / "foo" => Response.text("bar")
case Method.GET -> !! / "bar" => Response.text("foo")
}
private val app = Http.collectZIO[Request] {
case Method.GET -> !! / "random" => random.nextString(10).map(Response.text(_))
case Method.GET -> !! / "utc" => clock.currentDateTime.map(s => Response.text(s.toString))
}
private val server =
Server.port(PORT) ++
Server.paranoidLeakDetection ++
Server.app(fooBar ++ app)
override def run(args: List[String]): URIO[zio.ZEnv, ExitCode] = {
val nThreads: Int = args.headOption.flatMap(x => Try(x.toInt).toOption).getOrElse(0)
server.make
.use(start =>
console.putStrLn(s"Server started on port ${start.port}")
*> ZIO.never,
)
.provideCustomLayer(ServerChannelFactory.auto ++ EventLoopGroup.auto(nThreads))
.exitCode
}
}