Created
November 22, 2022 17:05
-
-
Save bilal-fazlani/9710d767852ff30c389e1a86396174a3 to your computer and use it in GitHub Desktop.
simple zio http server
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
import zio.http.* | |
import zio.http.service.* | |
import zio.* | |
object Main extends ZIOAppDefault { | |
private def portFromEnv: Option[Int] = sys.env.get("PORT").map(_.toInt) | |
val routes: Http[Any, Nothing, Request, Response] = Http.collectZIO[Request] { req => | |
val delay = req.url.queryParams | |
.get("delay") | |
.flatMap(x => x.headOption) | |
.flatMap(x => x.toIntOption) | |
.getOrElse(0) | |
.millis | |
ZIO.sleep(delay).as(Response.text("OK")) | |
} | |
def app(port: Int): Task[Unit] = (for { | |
_ <- Server.install(routes) | |
_ <- ZIO.logInfo(s"service started on port $port") | |
_ <- ZIO.never | |
} yield ()).provide(Server.live, ServerConfig.live(ServerConfig.default.port(port))) | |
val run = | |
val cliApp = cliApplication { | |
case CliOptions(Some(bindPort)) => app(bindPort) | |
case CliOptions(None) if portFromEnv.nonEmpty => app(portFromEnv.get) | |
case CliOptions(None) => ZIO.dieMessage("No port provided") | |
} | |
getArgs.flatMap(args => cliApp.run(args.toList)) | |
} |
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
lazy val zioVersion = "2.0.4" | |
lazy val devZio = "dev.zio" | |
lazy val root = project | |
.in(file(".")) | |
.settings( | |
name := "simple-http-server", | |
version := "0.1.0-SNAPSHOT", | |
organization := "com.bilal-fazlani", | |
scalaVersion := "3.2.0", | |
libraryDependencies ++= Seq( | |
devZio %% "zio" % zioVersion, | |
devZio %% "zio-http" % "0.0.3", | |
devZio %% "zio-cli" % "0.3.0-M01" | |
) | |
) |
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
import zio.* | |
import zio.cli.* | |
import zio.http.URL.Location | |
import zio.cli.HelpDoc.Span.text | |
val bindPort = Options.integer("bind").alias("port").map(_.toInt).optional ?? "bind port" | |
case class CliOptions(bind: Option[Int]) | |
val rootCommand = | |
Command("dummy-service", bindPort, Args.none).map( | |
bind => CliOptions(bind) | |
) | |
val cliApplication = | |
CliApp.make( | |
"dummy-service", | |
"0.1.0-SNAPSHOT", | |
text("dummy service"), | |
rootCommand | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment