Skip to content

Instantly share code, notes, and snippets.

@ayushmishra2005
Created November 11, 2017 17:33
Show Gist options
  • Save ayushmishra2005/162109cd525f3f095c2c78363376052c to your computer and use it in GitHub Desktop.
Save ayushmishra2005/162109cd525f3f095c2c78363376052c to your computer and use it in GitHub Desktop.
Akka HTTP Low-Level Server-Side API Sample
import akka.actor.ActorSystem
import akka.event.Logging
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.Sink
import scala.concurrent.Future
trait LowLevelAPIRoutes {
implicit val system = ActorSystem()
implicit val materializer = ActorMaterializer()
lazy val log = Logging(system, classOf[LowLevelAPIRoutes])
val requestHandler: HttpRequest => HttpResponse = {
case HttpRequest(GET, Uri.Path("/"), _, _, _) =>
HttpResponse(entity = HttpEntity(
ContentTypes.`text/html(UTF-8)`,
"<html><body>Hello!</body></html>"
))
case r: HttpRequest =>
r.discardEntityBytes()
HttpResponse(404, entity = "Unknown resource!")
}
}
object LowLevelServerAPISample extends App with LowLevelAPIRoutes {
implicit val executionContext = system.dispatcher
val host = "localhost"
val port = 8080
val serverSource = Http().bind(interface = host, port = port)
val bindingFuture: Future[Http.ServerBinding] =
serverSource.to(Sink.foreach { connection =>
println("Accepted new connection from " + connection.remoteAddress)
connection handleWithSyncHandler requestHandler
}).run()
bindingFuture.failed.foreach { ex =>
log.error(ex, "Failed to bind to {}:{}!", host, port)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment