【问题标题】:Crystal-lang serve index.htmlCrystal-lang 服务 index.html
【发布时间】:2016-12-29 07:14:09
【问题描述】:

我对这门语言有点陌生,我想开始破解一个非常简单的 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

我的目标是我不想列出目录,因为这样做会。如果public/ 提供index.html,我实际上想提供服务,而不必在URL 栏中放置index.html。让我们假设index.html 实际上确实存在于public/。任何指向可能有用的文档的指针?

【问题讨论】:

    标签: http crystal-lang


    【解决方案1】:

    这样的?

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多