From 4cd30839a589bfc3daa78273e2fbbd4e3c1135ac Mon Sep 17 00:00:00 2001 From: sdogruyol Date: Thu, 15 Sep 2016 19:35:34 +0300 Subject: [PATCH] Add gzip helper to enable/disable HTTP::DeflateHandler --- spec/helpers_spec.cr | 11 +++++++++++ src/kemal/helpers/helpers.cr | 11 +++++++++-- src/kemal/static_file_handler.cr | 3 +-- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/spec/helpers_spec.cr b/spec/helpers_spec.cr index e6de9d5..e3b7e6d 100644 --- a/spec/helpers_spec.cr +++ b/spec/helpers_spec.cr @@ -122,4 +122,15 @@ describe "Macros" do response.headers["Content-Length"].should eq("6") end end + + describe "#gzip" do + it "adds HTTP::DeflateHandler to handlers" do + gzip true + Kemal.config.handlers.last.is_a?(HTTP::DeflateHandler).should eq true + end + + it "doesn't add HTTP::DeflateHandler to handlers by default" do + Kemal.config.handlers.last.is_a?(HTTP::DeflateHandler).should eq false + end + end end diff --git a/src/kemal/helpers/helpers.cr b/src/kemal/helpers/helpers.cr index 6dba009..efe99f9 100644 --- a/src/kemal/helpers/helpers.cr +++ b/src/kemal/helpers/helpers.cr @@ -50,7 +50,7 @@ end # send_file env, "./path/to/file", "image/jpeg" def send_file(env, path : String, mime_type : String? = nil) file_path = File.expand_path(path, Dir.current) - mime_type ||= "application/octet-stream" + mime_type ||= "application/octet-stream" env.response.content_type = mime_type env.response.content_length = File.size(file_path) File.open(file_path) do |file| @@ -70,4 +70,11 @@ def send_file(env, data : Slice(UInt8), mime_type : String? = nil) env.response.content_type = mime_type env.response.content_length = data.bytesize env.response.write data -end \ No newline at end of file +end + +# Configures an `HTTP::Server::Response` to compress the response +# output, either using gzip or deflate, depending on the `Accept-Encoding` request header. +# It's disabled by default. +def gzip(status : Bool = false) + add_handler HTTP::DeflateHandler.new if status +end diff --git a/src/kemal/static_file_handler.cr b/src/kemal/static_file_handler.cr index f4115f8..f1d6f44 100644 --- a/src/kemal/static_file_handler.cr +++ b/src/kemal/static_file_handler.cr @@ -9,7 +9,7 @@ module Kemal return call_next(context) if context.request.path.not_nil! == "/" super end - + def mime_type(path) case File.extname(path) when ".txt" then "text/plain" @@ -23,6 +23,5 @@ module Kemal else "application/octet-stream" end end - end end