/
middleware.cr
49 lines (39 loc) · 1.53 KB
/
middleware.cr
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
require "./concerns/handler_response_converter"
module Marten
module Server
module Handlers
class Middleware
include ::HTTP::Handler
include HandlerResponseConverter
@middleware_chain : Array(Marten::Middleware)?
def call(context : ::HTTP::Server::Context)
response : HTTP::Response? = nil
# Call each middleware in order to let them process the incoming request and optionnaly bypass the routing
# mechanism by returning an early response. Each middleware should have access to the final response in order
# to process it if necessary (or to completely replace it!).
response = if middleware_chain.empty?
get_final_response(context)
else
middleware_chain.first.chain(context.marten.request, ->{ get_final_response(context) })
end
# At this point the final HTTP response has to be written to the server response.
convert_handler_response(context, response)
context
end
private def get_final_response(context)
call_next(context)
context.marten.response.not_nil!
end
private def middleware_chain
@middleware_chain ||= begin
chain = Marten.settings.middleware.map(&.new)
chain.each_cons_pair do |middleware, next_middleware|
middleware.next = next_middleware
end
chain
end
end
end
end
end
end