Class: Doraemon::HTTPServer

Inherits:
Object
  • Object
show all
Defined in:
lib/doraemon/http_server.rb

Instance Method Summary collapse

Constructor Details

#initialize(port = 8080, root) ⇒ HTTPServer

Returns a new instance of HTTPServer.



8
9
10
11
# File 'lib/doraemon/http_server.rb', line 8

def initialize(port=8080, root)
  @port = port
  @root = root
end

Instance Method Details

#startObject



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/doraemon/http_server.rb', line 13

def start

  server = WEBrick::HTTPServer.new :Port => @port
  server.mount_proc '/' do |req, resp|
    if req.path == '/'
      # 默认首页内容为下载证书页
      resp.body << File.read(File.join(__dir__, "web/download_cert.html"))
      resp.status = 200
    else
      path = File.join(@root, req.path)
      if File.exist?(path)
        resp.body << File.read(path)
        resp.status = 200
      else
        resp.body << "#{req.path} Not Found"
        resp.status = 404
      end
    end
  end
  
  server.mount_proc "/doraemon.crt" do |req, resp|
    resp.body << File.read(Cert.cert_path)
    resp.header["content-type"] = "application/x-x509-ca-cert"
    resp.status = 200
  end

  trap 'INT' do server.shutdown end
  server.start
end