From 05d55540b9cbcab9e9197390e2f6b2d0baeed820 Mon Sep 17 00:00:00 2001 From: Russell Smith Date: Thu, 30 Jun 2022 08:00:51 -0700 Subject: [PATCH] Enable option for index.html to be a directories default (#640) --- spec/static_file_handler_spec.cr | 9 +++++++++ src/kemal/config.cr | 2 +- src/kemal/static_file_handler.cr | 17 ++++++++++++++--- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/spec/static_file_handler_spec.cr b/spec/static_file_handler_spec.cr index e9307f6..309e10f 100644 --- a/spec/static_file_handler_spec.cr +++ b/spec/static_file_handler_spec.cr @@ -23,6 +23,15 @@ describe Kemal::StaticFileHandler do response.body.should eq(File.read("#{__DIR__}/static/dir/test.txt")) end + it "should serve the 'index.html' file when a directory is requested and index serving is enabled" do + serve_static({"dir_index" => true}) + response = handle HTTP::Request.new("GET", "/dir/") + response.status_code.should eq(200) + response.headers["Content-Type"].should eq "text/html" + response.headers["Etag"].should contain "W/\"" + response.body.should eq(File.read("#{__DIR__}/static/dir/index.html")) + end + it "should respond with 304 if file has not changed" do response = handle HTTP::Request.new("GET", "/dir/test.txt") response.status_code.should eq(200) diff --git a/src/kemal/config.cr b/src/kemal/config.cr index 4e62d8d..23372dd 100644 --- a/src/kemal/config.cr +++ b/src/kemal/config.cr @@ -31,7 +31,7 @@ module Kemal @host_binding = "0.0.0.0" @port = 3000 @env = ENV["KEMAL_ENV"]? || "development" - @serve_static = {"dir_listing" => false, "gzip" => true} + @serve_static = {"dir_listing" => false, "gzip" => true, "dir_index" => false} @public_folder = "./public" @logging = true @logger = nil diff --git a/src/kemal/static_file_handler.cr b/src/kemal/static_file_handler.cr index 109e971..ef592d0 100644 --- a/src/kemal/static_file_handler.cr +++ b/src/kemal/static_file_handler.cr @@ -36,7 +36,7 @@ module Kemal end file_path = File.join(@public_dir, expanded_path) - is_dir = Dir.exists? file_path + is_dir = Dir.exists?(file_path) if request_path != expanded_path redirect_to context, expanded_path @@ -44,8 +44,19 @@ module Kemal redirect_to context, expanded_path + '/' end - if Dir.exists?(file_path) - if config.is_a?(Hash) && config["dir_listing"] == true + if is_dir + if config.is_a?(Hash) && config.fetch("dir_index", false) && File.exists?(File.join(file_path, "index.html")) + file_path = File.join(@public_dir, expanded_path, "index.html") + + last_modified = modification_time(file_path) + add_cache_headers(context.response.headers, last_modified) + + if cache_request?(context, last_modified) + context.response.status_code = 304 + return + end + send_file(context, file_path) + elsif config.is_a?(Hash) && config.fetch("dir_listing", false) context.response.content_type = "text/html" directory_listing(context.response, request_path, file_path) else