Skip to content

Latest commit

 

History

History
136 lines (94 loc) · 4.12 KB

README.adoc

File metadata and controls

136 lines (94 loc) · 4.12 KB

Working with handlers (30 minutes)

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.

.1. Delegating to the next handler

Define a handler that prints out (println) the requested path, and then delegates to the next handler.

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.

.2. Responding to a specific path

Define a handler that renders "bar" when a request is sent to /foo

Then test it:

$ curl 0:5050/foo
bar

.3. Grouping handlers by path

Define the next handlers nested in the path /api.

.3.1. Group handlers by HTTP method

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.

To test them:

$ curl 0:5050/api/methods
GET /api/methods

$ curl -X POST 0:5050/api/methods
POST /api/methods

.3.2. Defining variable parts in the path

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

.3.3. Defining handlers in it’s own class

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().

To test it:

$ curl 0:5050/api/now
Thu Nov 26 17:55:44 CET 2015