Skip to content

Commit

Permalink
Enable option for index.html to be a directories default (#640)
Browse files Browse the repository at this point in the history
  • Loading branch information
ukd1 authored Jun 30, 2022
1 parent 268e501 commit 05d5554
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
9 changes: 9 additions & 0 deletions spec/static_file_handler_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/kemal/config.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 14 additions & 3 deletions src/kemal/static_file_handler.cr
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,27 @@ 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
elsif is_dir && !is_dir_path
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
Expand Down

0 comments on commit 05d5554

Please sign in to comment.