Reputation: 1214
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
Upvotes: 0
Views: 338
Reputation: 2376
You can use shivneri framework for this. Shivneri has inbuilt file server which is easy to configure & it serves index.html
Shivneri.folders = [{
path: "/",
folder: File.join(Dir.current, "assets"),
}]
For more info read doc - https://shivneriforcrystal.com/tutorial/file-server/
Upvotes: 0
Reputation: 3175
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
Upvotes: 2