Skip to content

Instantly share code, notes, and snippets.

@stonegao
Forked from robi42/rest.scala
Created October 9, 2011 16:05
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save stonegao/1273845 to your computer and use it in GitHub Desktop.
Save stonegao/1273845 to your computer and use it in GitHub Desktop.
Basic RESTful service with Finagle
class Respond extends Service[Request, Response] with Logger {
def apply(request: Request) = {
try {
request.method -> Path(request.path) match {
case GET -> Root / "todos" => Future.value {
val data = Todos.allAsJson
debug("data: %s" format data)
Responses.json(data, acceptsGzip(request))
}
case GET -> Root / "todos" / id => Future.value {
val todo = Todos get id
val data = todo.toJson
debug("data: %s" format data)
Responses.json(data, acceptsGzip(request))
}
case POST -> Root / "todos" => Future.value {
val content = request.contentString
val todo = Todos.fromJson(content, create = true)
val data = todo.toJson
Responses.json(data, acceptsGzip(request))
}
case PUT -> Root / "todos" / id => Future.value {
val content = request.contentString
val todo = Todos.fromJson(content, update = true)
val data = todo.toJson
debug("data: %s" format data)
Responses.json(data, acceptsGzip(request))
}
case DELETE -> Root / "todos" / id => Future.value {
Todos remove id
debug("data: %s" format id)
Response()
}
case _ =>
Future value Response(Http11, NotFound)
}
} catch {
case e: NoSuchElement => Future value Response(Http11, NotFound)
case e: Exception => Future.value {
val message = Option(e.getMessage) getOrElse "Something went wrong."
error("\nMessage: %s\nStack trace:\n%s"
.format(message, e.getStackTraceString))
Responses.error(message, acceptsGzip(request))
}
}
}
}
@huanzhang
Copy link

awesome

@OwenChang
Copy link

i like it

@jpzk
Copy link

jpzk commented Dec 10, 2014

perfect.

@prayagupa
Copy link

Where exists this Path??
import com.twitter.finagle.Path complains Type mismatch.

I'm using libraryDependencies += "com.twitter" %% "finagle-httpx" % "6.27.0"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment