Routing
Once you've built your Route
s, they can be used to route HTTP requests to specific application logic. Each route
contains enough information to match it against a request and extract the relevant parameters from the request's path
and query string, so all you need to do is specify the route-specific handling logic. Assuming you have the test routes:
import routing._
val Login = Method.GET / "login"
// Login: Route[GET, Unit] = /login
val Hello = Method.GET / "hello" / pathVar[String]("name")
// Hello: Route[GET, String] = /hello/<name: String>
val BlogPost = Method.GET / "post" / pathVar[String]("slug") :? queryParam[Int]("id")
// BlogPost: Route[GET, Tuple2[String, Int]] = /post/<slug: String>?<id: Int>
Then you can specify the handling logic for a given route by calling .handle
. The argument passed to with_
should be a function of the type Params => Out
where Params
is a tuple of the route's parameters and Out
is any
type you want to target with your handler.
Here's how you could handle the routes above, simply returning a String
for each route:
val handledLogin = Login.handle(_ => "Login page")
// handledLogin: Handled[String] {
type M >: Method <: Method
type P >: Params <: Params
type R >: Login <: Login
} = routing.Route$$anon$3@40f0e938
val handledHello = Hello.handle(name => s"Hello, $name")
// handledHello: Handled[String] {
type M >: Method <: Method
type P >: Params <: Params
type R >: Hello <: Hello
} = routing.Route$$anon$3@2398a64f
val handledBlogPost = BlogPost.handle { case (slug, id) =>
s"Blog post with id: $id, slug: $slug found"
}
// handledBlogPost: Handled[String] {
type M >: Method <: Method
type P >: Params <: Params
type R >: BlogPost <: BlogPost
} = routing.Route$$anon$3@34fe8f8
Of course the actual output type of your handlers will be dictated by the HTTP application framework you've chosen. See the implementations documentation for more examples.