Skip to content

Instantly share code, notes, and snippets.

@abacaj
Last active October 5, 2016 16:50
Show Gist options
  • Save abacaj/c4cafcdd8833467845cb to your computer and use it in GitHub Desktop.
Save abacaj/c4cafcdd8833467845cb to your computer and use it in GitHub Desktop.
Using a Map to hold routes with Akka
import scala.collection.mutable.Map
import scala.concurrent.ExecutionContextExecutor
import akka.http.scaladsl.model.ContentTypes
import akka.http.scaladsl.model.HttpEntity
import akka.http.scaladsl.model.HttpEntity.ChunkStreamPart
import akka.http.scaladsl.model.HttpEntity.apply
import akka.http.scaladsl.model.HttpProtocols
import akka.http.scaladsl.model.HttpResponse
import akka.http.scaladsl.model.StatusCode
import akka.http.scaladsl.model.Uri
import akka.stream.scaladsl.Flow
import akka.stream.scaladsl.Source
case class HttpHandler(implicit ec: ExecutionContextExecutor) {
val notImplemented = HttpResponse(StatusCode.int2StatusCode(404), entity = "Endpoint not implemented, try again with '/query'")
val routes = Map[Uri.Path, (HttpMethods.Method)]()
def addRoute(path: Uri.Path, method: HttpMethods.Method): Boolean = {
val _path = routes.get(path)
_path match {
case Some(p) =>
if (p.equals(method)) {
false
} else {
routes.put(path, (method))
true
}
case None =>
routes.put(path, (method))
true
}
}
def generateResponse(rs: Source[HttpEntity.ChunkStreamPart, Unit], status: Int, errorEntity: String = ""): HttpResponse = {
errorEntity match {
case "" =>
HttpResponse(StatusCode.int2StatusCode(status), entity = HttpEntity.Chunked(ContentTypes.`application/octet-stream`, rs) ,protocol = HttpProtocols.`HTTP/1.1`)
case _ =>
HttpResponse(StatusCode.int2StatusCode(status), entity = HttpEntity.apply(errorEntity) ,protocol = HttpProtocols.`HTTP/1.1`)
}
}
def generateResponseWithError(status: Int, errorEntity: String): HttpResponse = {
generateResponse(Source.empty, status, errorEntity)
}
}
import scala.concurrent.ExecutionContext
import akka.http.scaladsl.model.Uri
case object HttpRoutes {
implicit val ec = ExecutionContext.Implicits.global
val handler = HttpHandler()
handler.addRoute(Uri.Path("/query"), HttpMethods.POST)
}
import akka.actor.ActorSystem
import akka.stream.ActorMaterializer
object Main extends App {
implicit lazy val system = ActorSystem("service")
implicit val materializer = ActorMaterializer()
val handler = HttpRoutes.handler
HttpServer.bindServer(9995)(system, materializer, handler)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment