Skip to content

Instantly share code, notes, and snippets.

@rbuckland
Created April 6, 2016 02:12
Show Gist options
  • Save rbuckland/cfc0bb95ff765c2f30e562be1e27f8a9 to your computer and use it in GitHub Desktop.
Save rbuckland/cfc0bb95ff765c2f30e562be1e27f8a9 to your computer and use it in GitHub Desktop.
http4s example service
object BmpService {
// A Router can mount multiple services to prefixes. The request is passed to the
// service with the longest matching prefix.
def service(implicit executionContext: ExecutionContext = ExecutionContext.global): HttpService = Router(
"/api" -> apiService,
)
def apiService(implicit executionContext: ExecutionContext) = HttpService {
case req @ GET -> Root =>
// Supports Play Framework template -- see src/main/twirl.
Ok(html.index())
case _ -> Root =>
// The default route result is NotFound. Sometimes MethodNotAllowed is more appropriate.
MethodNotAllowed()
case GET -> Root / "ping" =>
// EntityEncoder allows for easy conversion of types to a response body
Ok("pong")
case GET -> Root / "future" =>
// EntityEncoder allows rendering asynchronous results as well
Ok(Future("Hello from the future!"))
case GET -> Root / "streaming" =>
// Its also easy to stream responses to clients
Ok(dataStream(100))
case req @ GET -> Root / "ip" =>
// Its possible to define an EntityEncoder anywhere so you're not limited to built in types
val json = Json.obj("origin" -> Json.string(req.remoteAddr.getOrElse("unknown")))
Ok(json)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment