Created
November 5, 2017 18:43
-
-
Save valenciaj/4a4bd82cf9060bb33a5d696204bd75e9 to your computer and use it in GitHub Desktop.
This file contains 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
class CachingHandler < Kemal::Handler | |
property cache : Hash(String, Bytes) | |
def initialize | |
@cache = Hash(String, Bytes).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 | |
context.response.write output | |
else | |
puts "Cache: false" | |
puts "Cache: building" | |
memBuffer = IO::Memory.new | |
context.response.output = IO::MultiWriter.new context.response.output, memBuffer | |
# continue | |
puts "Cache: continue" | |
ret = call_next context | |
puts "Cache: Response: #{ context.response.inspect }" | |
puts "Cache: memBuffer: #{ memBuffer.inspect }" | |
buffer = memBuffer.to_slice | |
# return | |
context.response.write(@cache[context.request.resource] = buffer) | |
context.response.flush | |
context.response.close | |
context.response.output.flush | |
context.response.output.close | |
ret | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment