Pipelines
A pipeline is a set of of transformations that is performed to a HTTP request. These transformations come in the form of a pipe. A pipe is a class which includes HTTP::Handler and implements the #call method.
You can use a handler to intercept any incoming request and modify the response. These can be used for request throttling, ip-based whitelisting, adding custom headers.
Every Amber application needs to define a pipeline with a set of pipes each pipeline allow a set of transformations to be applied to different sets of route, this give you granular control and explicitness of which transformation to run for each of the requests.
Above we define a pipeline called :web
as you can see the :web
pipeline transforms the request using a Logger, StaticFileHandler and a CompressHandler, all of which extends from the Crystal HTTP::Handler class.
Amber provides us some default pipes for a number of common tasks. In turn we can customize them as well as create new pipelines to meet our needs.
Pipe::Static serves static assets
Pipe::Logger logs incoming requests
Pipe::CORS Handler adds support for Cross Origin Resource Sharing.
Pipe::CSRF Handler adds support for Cross Site Request Forgery.
Pipe::Error Handler catches RouteNotFound and returns.
Pipe::Flash handler provides a mechanism to pass flash message between
Pipe::Session a plug that sets up session management.
With our :web
pipeline now define we can use it in our routes definitions.
Don't get rid of StaticController
if you need to serve static assets.
Sharing Pipelines
If you have two pipelines that share a lot of the same pipes, you can assign the shared pipes in one block: pipeline :web, :auth do ... end
Full example for config/routes.cr
:
Last updated