Crystal-lang服务index.html

时间:2016-12-29 07:14:10

标签: http crystal-lang

我对这门语言有点新意,我想开始在非常简单的HTTP服务器上进行攻击。我目前的代码如下:

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

我的目标是,我不想列出目录,因为这样做。我实际上想要index.html提供public/,而无需在网址栏中放置index.html。我们假设index.html确实存在于public/。任何可能有用的文档指针?

1 个答案:

答案 0 :(得分:3)

这样的东西?

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