Skip to content

Instantly share code, notes, and snippets.

@lanceon
Created April 21, 2017 07:31
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 lanceon/2398f5294a204db3c50e26b6548fe188 to your computer and use it in GitHub Desktop.
Save lanceon/2398f5294a204db3c50e26b6548fe188 to your computer and use it in GitHub Desktop.
Example: Minimal HTTP server for static content using Scala and Akka - HTTP
akka.http.server {
parsing {
max-content-length = 110M
}
}
akka {
loglevel = DEBUG
}
http {
ip = "localhost"
port = 4242
}
name := "nallo"
version := "1.0"
scalaVersion := "2.11.7"
// Akka
libraryDependencies ++= {
val akkaV = "2.3.12"
val akkaStreamV = "1.0"
val scalaTestV = "2.2.5"
Seq(
"com.typesafe.akka" %% "akka-actor" % akkaV,
"com.typesafe.akka" %% "akka-http-core-experimental" % akkaStreamV,
"com.typesafe.akka" %% "akka-http-experimental" % akkaStreamV,
"com.typesafe.akka" %% "akka-http-spray-json-experimental" % akkaStreamV,
)
}
// assembly name
assemblyJarName in assembly := "nallo.jar"
import akka.actor.{ActorSystem}
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.Directives._
import akka.stream.{ActorMaterializer}
import com.typesafe.config.ConfigFactory
import java.nio.file.{Files, Paths}
import akka.http.scaladsl.model.StatusCodes._
object routes {
val workingDirectory = System.getProperty("user.dir")
private def getExtensions(fileName: String) : String = {
val index = fileName.lastIndexOf('.')
if(index != 0) {
fileName.drop(index+1)
}else
""
}
private def getDefaultPage = {
val fullPath = List(Paths.get(workingDirectory + "/index.html"),Paths.get(workingDirectory + "/index.htm"))
val res = fullPath.filter(x => Files.exists(x))
if(!res.isEmpty)
res.head
else
Paths.get("")
}
def generate = {
logRequestResult("nallo-micro-http-server") {
get {
entity(as[HttpRequest]) { requestData =>
complete {
val fullPath = requestData.uri.path.toString match {
case "/"=> getDefaultPage
case "" => getDefaultPage
case _ => Paths.get(workingDirectory + requestData.uri.path.toString)
}
val ext = getExtensions(fullPath.getFileName.toString)
val c : ContentType = ContentType(MediaTypes.forExtension(ext).getOrElse(MediaTypes.`text/plain`))
val byteArray = Files.readAllBytes(fullPath)
HttpResponse(OK, entity = HttpEntity(c, byteArray))
}
}
}
}
}
}
object Main extends App {
implicit val system = ActorSystem()
implicit val executor = system.dispatcher
implicit val materializer = ActorMaterializer()
val config = ConfigFactory.load()
val logger = Logging(system, getClass)
Http().bindAndHandle(routes.generate, config.getString("http.ip"), config.getInt("http.port"))
}
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.1")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment