Skip to content

Instantly share code, notes, and snippets.

@xynophon
Last active February 13, 2017 10:27
Show Gist options
  • Select an option

  • Save xynophon/4fad9152a9d8aceffaf880ea247fdcbc to your computer and use it in GitHub Desktop.

Select an option

Save xynophon/4fad9152a9d8aceffaf880ea247fdcbc to your computer and use it in GitHub Desktop.
tumblr Colossus
import colossus._
import core._
import service._
import protocols.http._
import UrlParsing._
import HttpMethod._
import akka.actor.ActorSystem
import org.json4s.jackson.Serialization
class SampleService(context: ServerContext) extends HttpService(context) {
def fibonacci(i: Long): Long = i match {
case 1 | 2 => 1
case n => fibonacci(n-1) + fibonacci(n-2)
}
def handle = {
// http://localhost:9000/hello?country=japan&city=shibuya
case request @ Get on Root / "hello" => {
lazy val parameters = request.head.parameters.parameters.map{case (a, b) => (a -> b)}.toMap
// request.head.parameters.parameters == Vector((country, japan), (city, shibuya))
// request.head.parameters.parameters.map{case (a, b) => (a -> b)}.toMap == Map(country -> japan, city -> shibuya)
lazy val json = Serialization.write(parameters) // {"country":"japan","city":"shibuya"}
Callback.successful(request.ok(json))
}
// http://localhost:9000/fibonacci/10
case request @ Get on Root / "fibonacci" / Long(number) => if(number > 0){
val result = fibonacci(number)
Callback.successful(request.ok(result.toString)) // 55
} else {
Callback.successful(request.ok("number should be positive"))
}
}
}
class SampleInitializer(worker: WorkerRef) extends Initializer(worker) {
def onConnect = context => new SampleService(context)
}
object ColossusSample extends App {
implicit val actorSystem = ActorSystem()
implicit val io = IOSystem()
// http://localhost:9000
Server.start("hello-world", 9000){ worker => new SampleInitializer(worker) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment