diff --git a/zio-quickstart-restful-webservice/build.sbt b/zio-quickstart-restful-webservice/build.sbt index caeb664..a020f9a 100644 --- a/zio-quickstart-restful-webservice/build.sbt +++ b/zio-quickstart-restful-webservice/build.sbt @@ -14,3 +14,5 @@ libraryDependencies ++= Seq( ) resolvers ++= Resolver.sonatypeOssRepos("snapshots") + +Compile / mainClass := Some("dev.zio.quickstart.MainApp") diff --git a/zio-quickstart-restful-webservice/src/main/scala/dev/zio/quickstart/MainApp.scala b/zio-quickstart-restful-webservice/src/main/scala/dev/zio/quickstart/MainApp.scala index 8f26258..dd4cd2c 100644 --- a/zio-quickstart-restful-webservice/src/main/scala/dev/zio/quickstart/MainApp.scala +++ b/zio-quickstart-restful-webservice/src/main/scala/dev/zio/quickstart/MainApp.scala @@ -13,16 +13,33 @@ import zio.http._ object MainApp extends ZIOAppDefault: def run = - Server - .serve( - GreetingRoutes() ++ DownloadRoutes() ++ CounterRoutes() ++ UserRoutes() - ) - .provide( - Server.defaultWithPort(8080), + for { + serverFiber <- Server + .serve( + GreetingRoutes() ++ DownloadRoutes() ++ CounterRoutes() ++ UserRoutes() + ) + .provide( + Server.defaultWithPort(8080), - // An layer responsible for storing the state of the `counterApp` - ZLayer.fromZIO(Ref.make(0)), + // An layer responsible for storing the state of the `counterApp` + ZLayer.fromZIO(Ref.make(0)), - // To use the persistence layer, provide the `PersistentUserRepo.layer` layer instead - InmemoryUserRepo.layer - ) + // To use the persistence layer, provide the `PersistentUserRepo.layer` layer instead + InmemoryUserRepo.layer + ) + .fork + + // Add a shutdown hook to release the port on exit + _ <- ZIO.succeed { + java.lang.Runtime.getRuntime.addShutdownHook(new Thread { + override def run(): Unit = { + Unsafe.unsafe { implicit u => + Runtime.default.unsafe.run(serverFiber.interrupt) + } + } + }) + } + + // Wait for the server to exit + _ <- serverFiber.join + } yield ()