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.
Amber::Server.configure do |app|pipeline :web do# Plug is the method to use connect a pipe (middleware)# A plug accepts an instance of HTTP::Handler# plug Amber::Pipe::Params.newplug Amber::Pipe::Logger.newplug Amber::Pipe::Flash.newplug Amber::Pipe::Session.newplug Amber::Pipe::CSRF.newend# All static content will run these transformationspipeline :static doplug HTTP::StaticFileHandler.new("./public")plug HTTP::CompressHandler.newendroutes :static do# Each route is defined as follow# Verb resource : String, controller : Symbol, action : Symbolget "/*", StaticController, :indexendroutes :web doget "/", HomeController, :staticendend
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.
:web pipeline now define we can use it in our routes definitions.
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
Amber::Server.configure do |app|pipeline :web, :auth doplug Amber::Pipe::Logger.newplug Amber::Pipe::Flash.newplug Amber::Pipe::Session.newplug Amber::Pipe::CSRF.newendpipeline :auth doplug Authenticate.newendroutes :web doget "/", HomeController, :staticendroutes :auth doget "/admin", AdminController, :dashboardendend