Kemal caching responses with handler middleware
I'm trying to do caching of some GET request with Kemal.
class CachingHandler < Kemal::Handler
property cache : Hash(String, IO::Memory)
def initialize
@cache = Hash(String, IO::Memory).new
end
def call(context)
puts "Caching"
puts "Key: #{ context.request.resource }"
if output = @cache[context.request.resource]?
puts "Cache: true"
IO.copy output, context.response.output
else
puts "Cache: false"
puts "Cache: building"
context.response.output =
@cache[context.request.resource] = IO::Memory.new
# continue
puts "Cache: continue"
call_next context
end
end
end
But in the first request the browser it's always waiting a response. And in the second request send a "Closed stream (IO::Error)" error.