Skip to content

Instantly share code, notes, and snippets.

@davideanastasia
Created December 10, 2015 22:09
Show Gist options
  • Save davideanastasia/3936f6ebcf491c56df86 to your computer and use it in GitHub Desktop.
Save davideanastasia/3936f6ebcf491c56df86 to your computer and use it in GitHub Desktop.
Akka Faffing
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.{Uri, StatusCodes, HttpResponse, HttpRequest}
import akka.stream.ActorMaterializer
import scala.concurrent.duration._
import scala.concurrent.Await
import scala.util.{Success, Try, Failure}
case class IpAddress(ip: String)
object LookupMicroServiceFlow {
// With an async handler, we use futures. Threads aren't blocked.
def asyncHandler(request: HttpRequest): HttpResponse = {
// we match the request, and some simple path checking
request match {
// match GET pat. Return a single ticker
case HttpRequest(GET, Uri.Path("/get"), _, _, _) => {
// next we match on the query parameter
request.uri.query.get("id") match {
// if we find the query parameter
case Some(queryParameter) => HttpResponse(entity = queryParameter)
// if the query parameter isn't there
case None => HttpResponse(status = StatusCodes.OK)
}
}
// Simple case that matches everything, just return a not found
case HttpRequest(_, _, _, _, _) => HttpResponse(status = StatusCodes.NotFound)
}
}
}
object LookupMicroService extends App {
implicit val system = ActorSystem("akka-http-sample")
implicit val executor = system.dispatcher
implicit val materializer = ActorMaterializer()
val binding = Http().bindAndHandleSync(
LookupMicroServiceFlow.asyncHandler,
interface = "localhost",
port = 9001
)
// binding is a future, we assume it's ready within a second or timeout
Try(Await.result(binding, 1 second)) match {
case Failure(ex) =>
println("Server took to long to startup, shutting down")
system.shutdown()
case Success(_) =>
println("Server online at http://localhost:9001")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment