From e4da65f1f2113aa19a05e564866b13280a373e27 Mon Sep 17 00:00:00 2001 From: Sdogruyol Date: Thu, 10 Dec 2015 21:15:28 +0200 Subject: [PATCH] Refactor static file handler --- src/kemal.cr | 2 +- src/kemal/macros.cr | 2 +- src/kemal/static_file_handler.cr | 10 ++++++++++ src/kemal/static_handler.cr | 32 -------------------------------- 4 files changed, 12 insertions(+), 34 deletions(-) create mode 100644 src/kemal/static_file_handler.cr delete mode 100644 src/kemal/static_handler.cr diff --git a/src/kemal.cr b/src/kemal.cr index 8495dd3..5064ec1 100644 --- a/src/kemal.cr +++ b/src/kemal.cr @@ -17,7 +17,7 @@ at_exit do config = Kemal.config logger = Kemal::Logger.new config.add_handler logger - config.add_handler Kemal::StaticHandler.new("./public") + config.add_handler Kemal::StaticFileHandler.new("./public") config.add_handler Kemal::Handler::INSTANCE server = HTTP::Server.new(config.port, config.handlers) diff --git a/src/kemal/macros.cr b/src/kemal/macros.cr index 7a42b1e..85ecfea 100644 --- a/src/kemal/macros.cr +++ b/src/kemal/macros.cr @@ -1,4 +1,4 @@ macro redirect(url) env.response.headers.add "Location", {{url}} env.response.status_code = 301 -end \ No newline at end of file +end diff --git a/src/kemal/static_file_handler.cr b/src/kemal/static_file_handler.cr new file mode 100644 index 0000000..21f8ad2 --- /dev/null +++ b/src/kemal/static_file_handler.cr @@ -0,0 +1,10 @@ +require "http/server" +require "ecr/macros" + +class Kemal::StaticFileHandler < HTTP::Handler + def call(request) + request_path = request.path.not_nil! + return call_next(request) if request_path == "/" + super + end +end diff --git a/src/kemal/static_handler.cr b/src/kemal/static_handler.cr deleted file mode 100644 index f5d433b..0000000 --- a/src/kemal/static_handler.cr +++ /dev/null @@ -1,32 +0,0 @@ -require "http/server" -require "ecr/macros" - -class Kemal::StaticHandler < HTTP::Handler - - def initialize(@publicdir) - end - - def call(request) - request_path = request.path.not_nil! - - # Call next handler for processing - return call_next(request) unless request_path.starts_with? "/public" - file = request_path.split("/public/")[1] if request_path.starts_with?("/public") - file_path = File.expand_path("public/#{file}", Dir.working_directory) - if File.exists?(file_path) - HTTP::Response.new(200, File.read(file_path), HTTP::Headers{"Content-Type": mime_type(file_path)}) - else - call_next(request) - end - end - - private def mime_type(path) - case File.extname(path) - when ".txt" then "text/plain" - when ".htm", ".html" then "text/html" - when ".css" then "text/css" - when ".js" then "application/javascript" - else "application/octet-stream" - end - end -end