Skip to content

Instantly share code, notes, and snippets.

@dacr
Last active June 25, 2023 15:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dacr/75a26afb9d6cb9c99d78d639150e701b to your computer and use it in GitHub Desktop.
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
// 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