Last active
February 3, 2026 20:19
-
-
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/ade2171c25a414e56f739854dfb8a6e6f8422c39
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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 License Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | |
| // 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