Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active May 25, 2024 10:19
Show Gist options
  • Save dacr/2ffa85b6d75037a15cfe53289e05aae2 to your computer and use it in GitHub Desktop.
Save dacr/2ffa85b6d75037a15cfe53289e05aae2 to your computer and use it in GitHub Desktop.
ZIO learning - zhttp - simplest http server / published by https://github.com/dacr/code-examples-manager #a9a3d6d7-41e1-419f-bc6d-2f06930a92b9/21b6b7b7dce9e49f112908234816b4b7da07ca5
// summary : ZIO learning - zhttp - simplest 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 : a9a3d6d7-41e1-419f-bc6d-2f06930a92b9
// created-on : 2021-05-27T12:29:29Z
// managed-by : https://github.com/dacr/code-examples-manager
// run-with : scala-cli $file
// usage-example : scala-cli zio-learning-zhttp-server-1.sc -- 60
// test-with : curl http://127.0.0.1:8080/
// ---------------------
//> using scala "3.4.2"
//> using dep "dev.zio::zio-http:3.0.0-RC1"
// ---------------------
import zio.*, zio.http.*, zio.http.Path.root
object Main extends ZIOAppDefault {
val routes = Http.collect[Request] {
case Method.GET -> root => Response.text("Hello World!")
case Method.GET -> root / "json" => Response.json("""{"greetings": "Hello World!"}""")
}
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/")
args <- getArgs
autoExitDelay = args.headOption.map(_.toInt).getOrElse(5)
_ <- Console.printLine(s"Auto exiting in $autoExitDelay seconds")
_ <- Server.serve(routes.withDefaultErrorResponse).timeout(autoExitDelay.seconds)
} yield ()
override def run = serverLogic.provideSome[ZIOAppArgs](Server.default) // We do want to provide ZIOAppArgs...
}
Main.main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment