Created
April 8, 2014 15:55
-
-
Save vkostyukov/10147216 to your computer and use it in GitHub Desktop.
Finagle's Routing Service Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.twitter.finagle.builder.ServerBuilder | |
import com.twitter.finagle.http.path._ | |
import com.twitter.finagle.http.service.RoutingService | |
import com.twitter.finagle.Service | |
import com.twitter.finagle.http._ | |
import com.twitter.util.Future | |
import java.net.InetSocketAddress | |
import scala.util.parsing.json.JSONObject | |
object Main extends App { | |
def userService(id: Int) = new Service[Request, Response] { | |
def apply(req: Request): Future[Response] = { | |
val rep = Response(Version.Http11, Status.Ok) | |
// scala.util.parsing.json.JSONObject | |
val o = JSONObject(Map("id" -> id, "name" -> "John Smith")) | |
rep.setContentTypeJson() | |
rep.setContentString(o.toString) | |
Future(rep) | |
} | |
} | |
def echoService(message: String) = new Service[Request, Response] { | |
def apply(req: Request): Future[Response] = { | |
val rep = Response(req.getProtocolVersion(), Status.Ok) | |
rep.setContentString(message) | |
Future(rep) | |
} | |
} | |
val blackHole = new Service[Request, Response] { | |
def apply(request: Request): Future[Response] = Future.never | |
} | |
val router = RoutingService.byPathObject[Request] { | |
case Root / "user" / Integer(id) => userService(id) | |
case Root / "echo"/ message => echoService(message) | |
case _ => blackHole | |
} | |
val server = ServerBuilder() | |
.codec(RichHttp[Request](Http())) | |
.bindTo(new InetSocketAddress(8080)) | |
.name("router") | |
.build(router) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment