Skip to content

Instantly share code, notes, and snippets.

@jwaldrip
Created February 17, 2018 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jwaldrip/401d4e84c6018f60ffee0d1d824753f3 to your computer and use it in GitHub Desktop.
Save jwaldrip/401d4e84c6018f60ffee0d1d824753f3 to your computer and use it in GitHub Desktop.
A Linkless Middleware Example
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