Last active
June 25, 2023 15:32
-
-
Save dacr/75a26afb9d6cb9c99d78d639150e701b to your computer and use it in GitHub Desktop.
Simplest static resources http server example using akka-http framework with shutdown support and root redirect. / published by https://github.com/dacr/code-examples-manager #e40a4c3a-fa13-4755-a01b-368ddce90f98/4765d7192a75f3fa497ff105a143f53839a517d
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 : Simplest static resources http server example using akka-http framework with shutdown support and root redirect. | |
// keywords : scala, actors, akka-http, http-server | |
// 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 : e40a4c3a-fa13-4755-a01b-368ddce90f98 | |
// created-on : 2018-06-30T15:43:05Z | |
// managed-by : https://github.com/dacr/code-examples-manager | |
// execution : scala ammonite script (http://ammonite.io/) - run as follow 'amm scriptname.sc' | |
import $ivy.`com.typesafe.akka::akka-http:10.2.4` | |
import $ivy.`com.typesafe.akka::akka-stream:2.6.13` | |
import akka.http.scaladsl._ | |
import akka.http.scaladsl.server.Directives._ | |
import akka.http.scaladsl.model.StatusCodes | |
import scala.concurrent.Await | |
import scala.concurrent.duration.Duration | |
object StaticServer { | |
implicit val system = akka.actor.ActorSystem("MySystem") | |
implicit val executionContext = system.dispatcher | |
val stopHook = path("shutdown") { get { complete { shutdown() ; "OK" } } } | |
val statics = pathPrefix("browse") { getFromBrowseableDirectory(".") } | |
val home = pathPrefix("") {redirect("/browse", StatusCodes.TemporaryRedirect)} | |
val bindingFuture = Http().newServerAt("0.0.0.0", 8080).bind(stopHook ~ statics ~ home) | |
bindingFuture.andThen{case _ => println("Ready.")} | |
def shutdown():Unit = bindingFuture.flatMap(_.unbind()).onComplete { _ => system.terminate() } | |
// Utility function to avoid default exit | |
def waitForShutdown(): Unit = Await.ready(system.whenTerminated, Duration.Inf) | |
} | |
StaticServer.waitForShutdown() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment