2016-12-29 57 views
2

我对这门语言有点新,我想开始在非常简单的HTTP服务器上进行黑客攻击。我当前的代码如下所示:Crystal-lang服务index.html

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放置在URL栏中。我们假设index.html确实存在于public/。任何指向可能有用的文档的指针?

回答

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