Created
February 17, 2018 18:08
-
-
Save jwaldrip/401d4e84c6018f60ffee0d1d824753f3 to your computer and use it in GitHub Desktop.
A Linkless Middleware Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "http" | |
module Middleware | |
struct Chain | |
alias Link = Middleware | HTTP::Handler | HTTP::Handler::Proc | |
@links: Array(Link) = [] of Link | |
def initialize(links) | |
links.each do |link| | |
@links << (link.is_a?(HTTP::Handler) ? link.dup : link) | |
end | |
end | |
def call(c : HTTP::Server::Context) : Nil | |
call_link @links.shift?, c | |
end | |
def call_link(middleware : Middleware, c : HTTP::Server::Context) | |
middleware.call(c) do |c| | |
self.call(c) | |
end | |
end | |
def call_link(proc : HTTP::Handler::Proc, c : HTTP::Server::Context) | |
proc.call(c) | |
end | |
def call_link(handler : HTTP::Handler, c) | |
handler.next = ->(c : HTTP::Server::Context){ self.call(c) } | |
handler.call(c) | |
end | |
def call_link(proc : Nil, c : HTTP::Server::Context) | |
end | |
def to_proc | |
-> (c : HTTP::Server::Context) { self.class.new(@links).call(c) } | |
end | |
end | |
abstract def call(c : HTTP::Server::Context, &block : HTTP::Server::Context -> Nil) | |
end | |
struct MiddlewareOne | |
include Middleware | |
def call(c : HTTP::Server::Context) | |
c.response.puts "1: on request" | |
yield c | |
c.response.puts "1: on response" | |
end | |
end | |
struct MiddlewareTwo | |
include Middleware | |
def call(c : HTTP::Server::Context) | |
c.response.puts "2: on request" | |
yield c | |
c.response.puts "2: on response" | |
end | |
end | |
struct MiddlewareThree | |
include Middleware | |
def call(c : HTTP::Server::Context) | |
c.response.puts "3: on request" | |
yield c | |
c.response.puts "3: on response" | |
end | |
end | |
app = ->(c : HTTP::Server::Context){ | |
c.response.puts "Hello World" | |
nil | |
} | |
chain = Middleware::Chain.new([ | |
HTTP::LogHandler.new, | |
MiddlewareOne.new, | |
MiddlewareTwo.new, | |
MiddlewareThree.new, | |
app | |
]) | |
HTTP::Server.new(8080, chain.to_proc).listen |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment