Search code examples
rubycallbackwebserver

Ruby webserver - callback when the request has been served


Is there any way to know when a request has been served by a ruby webserver (webrick, evma_httpserver, whatever?)

Goal is to serve 2 static files and shutdown server after the second file has been served to the client. It seems i can not find anything related to this, so any pointers are welcome..


Solution

  • Just shutdown server then the second file is served. Here is an example:

    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
    

    Run 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.
    $~
    

    Both files are served:

    enter image description here