Ruby WebServer-在服务请求后回调

时间:2018-09-26 07:38:15

标签: ruby callback webserver

有没有办法知道ruby Web服务器(webrick,evma_httpserver等)何时响应了请求?

目标是在将第二个文件提供给客户端之后,提供2个静态文件和关闭服务器。 看来我找不到与此相关的任何内容,因此欢迎使用任何指针。

1 个答案:

答案 0 :(得分:1)

仅关闭服务器,然后提供第二个文件。这是一个示例

server.rb

require 'webrick'

server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => '/'
server.mount_proc '/' do |req, res|
  # response with simple html body
  res.body = '
  <html>
    <head>
      <title>My Webpage</title>
      <!-- first file -->
      <link rel="stylesheet" href="/one_file.css" type="text/css">
      <!-- second file -->
      <link rel="stylesheet" href="/second_file.css" type="text/css">
    </head>
    <body>
      <h1>Hello world!</h1>
    </body>
  </html>'
end
server.mount_proc '/one_file.css' do |req, res|
  res.body = 'h1 { color: blue; }'
end
server.mount_proc '/second_file.css' do |req, res|
  res.body = 'h1 { color: red; }'
  puts "Shutdown server !"
  server.shutdown
end
server.start

运行server.rb:

$~  ruby server.rb 
[2018-09-26 11:02:21] INFO  WEBrick 1.3.1
[2018-09-26 11:02:21] INFO  ruby 2.4.1 (2017-03-22) [x86_64-linux]
[2018-09-26 11:02:21] INFO  WEBrick::HTTPServer#start: pid=24224 port=8000
::1 - - [26/Sep/2018:11:02:24 MSK] "GET / HTTP/1.1" 200 262
- -> /
::1 - - [26/Sep/2018:11:02:24 MSK] "GET /one_file.css HTTP/1.1" 200 19
http://localhost:8000/ -> /one_file.css
::1 - - [26/Sep/2018:11:02:24 MSK] "GET /second_file.css HTTP/1.1" 200 18
http://localhost:8000/ -> /second_file.css
::1 - - [26/Sep/2018:11:02:24 MSK] "GET /favicon.ico HTTP/1.1" 200 262
http://localhost:8000/ -> /favicon.ico
[2018-09-26 11:02:25] INFO  going to shutdown ...
[2018-09-26 11:02:25] INFO  WEBrick::HTTPServer#start done.
$~

两个文件均被投放:

enter image description here

相关问题