Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active October 8, 2023 08:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/e13874500ac830039c7d4f9a965347f1 to your computer and use it in GitHub Desktop.
Save dacr/e13874500ac830039c7d4f9a965347f1 to your computer and use it in GitHub Desktop.
ZIO learning - zhttp - playing with http server / published by https://github.com/dacr/code-examples-manager #df382d02-6f01-417e-bf2a-b8c4a7e401d9/504005b0e87ca98064bc5d2083ab4bb090f33b57
// summary : ZIO learning - zhttp - playing with http server
// keywords : scala, zio, learning, pure-functional, async, http-server, zhttp, @testable, @exclusive
// publish : gist
// authors : David Crosson
// license : Apache NON-AI License Version 2.0 (https://raw.githubusercontent.com/non-ai-licenses/non-ai-licenses/main/NON-AI-APACHE2)
// id : df382d02-6f01-417e-bf2a-b8c4a7e401d9
// created-on : 2022-01-15T08:48:21+01:00
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// test-with : curl http://127.0.0.1:8080/uuid
// ---------------------
//> using scala "3.2.2"
//> using dep "dev.zio::zio-http:3.0.0-RC1"
// ---------------------
import zio.*, zio.http.*, zio.ZIO.succeed
object Main extends ZIOAppDefault {
val routes = Http.collectZIO[Request] {
case Method.GET -> root => succeed(Response.text("Hello World!"))
case Method.GET -> root / "json" => succeed(Response.json("""{"greetings": "Hello World!"}"""))
case Method.GET -> root / "uuid" => Random.nextUUID.map(uuid => Response.text(uuid.toString))
}
val serverLogic = for {
config <- ZIO.config(Server.Config.config)
port = config.address.getPort
_ <- Console.printLine(s"Server listening on http://127.0.0.1:$port/")
_ <- Server.serve(routes.withDefaultErrorResponse)
} yield ()
override def run =
for {
args <- getArgs
listenOn = args.headOption.map(_.toInt).getOrElse(8080)
autoExitDelay = args.drop(1).headOption.map(_.toInt).getOrElse(5)
_ <- Console.printLine(s"Auto exiting in $autoExitDelay seconds")
_ <- serverLogic.timeout(autoExitDelay.seconds).provide(Server.defaultWithPort(listenOn))
} yield ()
}
Main.main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment