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.
1
Amber::Server.configure do |app|
2
pipeline :web do
3
# Plug is the method to use connect a pipe (middleware)
4
# A plug accepts an instance of HTTP::Handler
5
# plug Amber::Pipe::Params.new
6
plug Amber::Pipe::Logger.new
7
plug Amber::Pipe::Flash.new
8
plug Amber::Pipe::Session.new
9
plug Amber::Pipe::CSRF.new
10
end
11
12
# All static content will run these transformations
13
pipeline :static do
14
plug HTTP::StaticFileHandler.new("./public")
15
plug HTTP::CompressHandler.new
16
end
17
18
routes :static do
19
# Each route is defined as follow
20
# Verb resource : String, controller : Symbol, action : Symbol
21
get "/*", StaticController, :index
22
end
23
24
routes :web do
25
get "/", HomeController, :static
26
end
27
end
Copied!
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:
1
Amber::Server.configure do |app|
2
pipeline :web, :auth do
3
plug Amber::Pipe::Logger.new
4
plug Amber::Pipe::Flash.new
5
plug Amber::Pipe::Session.new
6
plug Amber::Pipe::CSRF.new
7
end
8
9
pipeline :auth do
10
plug Authenticate.new
11
end
12
13
routes :web do
14
get "/", HomeController, :static
15
end
16
17
routes :auth do
18
get "/admin", AdminController, :dashboard
19
end
20
end
Copied!
Last modified 3yr ago
Copy link