0

I'm trying to learn Crystal. As an exercise, I'm making a simple web application, which needs to serve a file (called index.html).

Unfortunately, I can only figure out how to serve the directory the file resides in. This is hat you get if you load up http://localhost:

Directory listing for /
    index.html
    style.css

But I of course want to see the contents of index.html instead.

My code is as follows:

require "http/server"

port = 3000

server = HTTP::Server.new("127.0.0.1", port, [
  HTTP::ErrorHandler.new,
  HTTP::LogHandler.new,
  HTTP::CompressHandler.new,
  HTTP::StaticFileHandler.new("./assets"),
])

puts "listening on http://localhost:#{port}"

server.listen
Jones
  • 1,154
  • 1
  • 10
  • 35

2 Answers2

2

Crystal's StaticFileHandler currently doesn't serve index.html in directories which contain it. Instead it serves a directory listing as you have found out. Unfortunately there's no way to make StaticFileHandler do what you want.

However, if you only need to serve a top-level index.html, you can adapt your code to serve the file in a handler like so:

require "http/server"

port = 3000

server = HTTP::Server.new("127.0.0.1", port, [
  HTTP::ErrorHandler.new,
  HTTP::LogHandler.new,
  HTTP::CompressHandler.new,
  HTTP::StaticFileHandler.new("./assets"),
]) do |context|
  if context.request.path = "/" && context.request.method == "GET"
    context.response.content_type = "text/html"

    File.open("./assets/index.html") do |file|
      IO.copy(file, context.response)
    end
  end
end

puts "listening on http://localhost:#{port}"

server.listen
Stephie
  • 3,135
  • 17
  • 22
  • I'd recommend creating an issue for adding support for this to StaticFileHandler here: https://github.com/crystal-lang/crystal/issues – Stephie Mar 18 '17 at 19:12
  • So I can't get this to work. As far as I can tell, none of the code in the `do |context|` block is running. I put a few puts statements around and none of the are producing output. And I still just get a directory when loading the root. – Jones Mar 19 '17 at 15:06
  • I needed to both use your code, and remove the StaticFileHandler – Jones Mar 19 '17 at 15:32
0

You can use shivneri framework for this. Shivneri has inbuilt file server which is easy to configure & it serves index.html

How to configure

Shivneri.folders = [{
    path: "/",
    folder:  File.join(Dir.current, "assets"),
}]

For more info read doc - https://shivneriforcrystal.com/tutorial/file-server/

Ujjwal Kumar Gupta
  • 2,308
  • 1
  • 21
  • 32