Ratpack is built on top of Netty, a non-blocking HTTP server. Once the Ratpack server is started, it will listen for incoming requests, and for each, will execute all the handlers defined in the handler chain.
Note
|
Ratpack is not Servlet API-based, so don’t expect things HttpServletRequest or HttpSession . However, you can think of handlers as a mix of a Servlet and a Filter.
|
Handlers are functions composed in a handler chain. A handler can do one of the following:
-
Respond to the request.
-
Delegate to the next handler in the chain.
-
Insert more handlers in the chain and delegate to them.
Each handler receives a Context
object to interact with the request
/response
objects, the chain, etc. All the methods of the Context
are automatically available in your Ratpack.groovy
DSL:
ratpack {
handlers {
all {
response.send("Hello World") //Equivalent to context.response.send("Hello World")
}
}
}
Tip
|
Handlers are evaluated and executed in the order they are defined. Handlers without path specified should be placed at the bottom of the chain. |
Using the skeleton provided, work in the Ratpack.groovy
file to complete the following exercises.
Define a handler that prints out (println
) the requested path, and then delegates to the next handler.
Tip
|
You can test it by requesting some URL:
$ curl 0:5050/some/path
And you should see /some/path
in the server logs.
Note
|
You will also see a 404 error, as there is no downstream handler defined yet. You can ignore it for the moment. |
Define a handler that renders "bar"
when a request is sent to /foo
Tip
|
Then test it:
$ curl 0:5050/foo
bar
Define the next handlers nested in the path /api
.
Define 2 handlers for the path /api/methods
:
-
If the request is GET, the response is
GET /api/methods
. -
If the request is POST, the response is
POST /api/methods
.
Tip
|
|
To test them:
$ curl 0:5050/api/methods
GET /api/methods
$ curl -X POST 0:5050/api/methods
POST /api/methods
Define a handler for the path /api/<USERNAME>
, where <USERNAME>
can be any String. The response must be Hello, <USERNAME>
To test it:
$ curl 0:5050/api/alvaro.sanchez
Hello alvaro.sanchez
For other than simple examples, it is often a good practice to define handlers in their own class under src/groovy
.
Create a handler (implementing Handler
interface) for the path /api/now/
and respond with a new Date()
.
Tip
|
To test it:
$ curl 0:5050/api/now
Thu Nov 26 17:55:44 CET 2015