Crystal-lang serve index.html

337 Views Asked by At

I'm a bit new to the language, and I want to start hacking away at a very simple HTTP server. My current code looks like this:

require "http/server"

port = 8080
host = "127.0.0.1"
mime = "text/html"

server = HTTP::Server.new(host, port, [
  HTTP::ErrorHandler.new,
  HTTP::LogHandler.new,
  HTTP::StaticFileHandler.new("./public"),
  ]) do |context|
  context.response.content_type = mime
end

puts "Listening at #{host}:#{port}"
server.listen

My goal here is that I don't want to list the directory, as this will do. I actually want to serve index.html if it is available at public/, without having to place index.html in the URL bar. Let's assume that index.html actually does exist at public/. Any pointers to docs that might be useful?

1

There are 1 best solutions below

0
On BEST ANSWER

Something like this?

require "http/server"

port = 8080
host = "127.0.0.1"
mime = "text/html"

server = HTTP::Server.new(host, port, [
  HTTP::ErrorHandler.new,
  HTTP::LogHandler.new,
]) do |context|
  req = context.request

  if req.method == "GET" && req.path == "/public"
    filename = "./public/index.html"
    context.response.content_type = "text/html"
    context.response.content_length = File.size(filename)
    File.open(filename) do |file|
      IO.copy(file, context.response)
    end
    next
  end

  context.response.content_type = mime
end

puts "Listening at #{host}:#{port}"
server.listen