Skip to content

Instantly share code, notes, and snippets.

@stig
Created October 5, 2013 21:05

Revisions

  1. stig created this gist Oct 5, 2013.
    53 changes: 53 additions & 0 deletions Ping.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,53 @@
    package example

    import akka.actor._
    import akka.actor.ActorDSL._
    import akka.io.IO
    import akka.pattern.ask
    import akka.util.Timeout
    import scala.concurrent.duration._
    import spray.can.Http
    import spray.http.StatusCodes
    import spray.httpx.SprayJsonSupport._
    import spray.routing.HttpServiceActor
    import spray.json._
    import spray.routing._
    import spray.http._
    import DefaultJsonProtocol._

    case class Pong(ping: String)

    object Ping extends App {

    implicit val system = ActorSystem("demo")

    val model = actor(new Act {
    become {
    case req: String => sender ! Pong(req)
    }
    })

    val service = system.actorOf(Props(new Service(model)))

    IO(Http) ! Http.Bind(service, interface = "localhost", port = 8080)
    }

    class Service(model: ActorRef) extends HttpServiceActor {
    import context.dispatcher

    implicit val resFmt = jsonFormat1(Pong)
    implicit val timeout = Timeout(1.second)

    def receive = runRoute(
    path(Segment) { segment =>
    get {
    complete {
    (model ? segment).map {
    case Pong(x) if x == "bad" => StatusCodes.Conflict -> Pong("BAD REQUEST")
    case r @ Pong(_) => StatusCodes.OK -> r
    }
    }
    }
    })
    }