Enable option for index.html to be a directories default (#640)

This commit is contained in:
Russell Smith 2022-06-30 08:00:51 -07:00 committed by GitHub
parent 268e501a63
commit 05d55540b9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 4 deletions

View file

@ -23,6 +23,15 @@ describe Kemal::StaticFileHandler do
response.body.should eq(File.read("#{__DIR__}/static/dir/test.txt")) response.body.should eq(File.read("#{__DIR__}/static/dir/test.txt"))
end 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 it "should respond with 304 if file has not changed" do
response = handle HTTP::Request.new("GET", "/dir/test.txt") response = handle HTTP::Request.new("GET", "/dir/test.txt")
response.status_code.should eq(200) response.status_code.should eq(200)

View file

@ -31,7 +31,7 @@ module Kemal
@host_binding = "0.0.0.0" @host_binding = "0.0.0.0"
@port = 3000 @port = 3000
@env = ENV["KEMAL_ENV"]? || "development" @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" @public_folder = "./public"
@logging = true @logging = true
@logger = nil @logger = nil

View file

@ -36,7 +36,7 @@ module Kemal
end end
file_path = File.join(@public_dir, expanded_path) 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 if request_path != expanded_path
redirect_to context, expanded_path redirect_to context, expanded_path
@ -44,8 +44,19 @@ module Kemal
redirect_to context, expanded_path + '/' redirect_to context, expanded_path + '/'
end end
if Dir.exists?(file_path) if is_dir
if config.is_a?(Hash) && config["dir_listing"] == true 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" context.response.content_type = "text/html"
directory_listing(context.response, request_path, file_path) directory_listing(context.response, request_path, file_path)
else else