3

我对这门语言有点陌生,我想开始破解一个非常简单的 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.htmlURL 栏中。让我们假设它index.html确实存在于public/。任何指向可能有用的文档的指针?

4

1 回答 1

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
于 2016-12-29T11:04:34.303 回答