Search code examples
rubyrubygemsserverfile-handlingwebrick

Serving files & handling requests with Webrick on same port


Hi I have a need to be able to receive requests from GitLab (body => JSON) as well as serve files on same port. I am trying to use Webrick for this purpose. I can do these separately.

To serve files I do:

server = WEBrick::HTTPServer.new(:Port => 3030, :DocumentRoot => '/')
server.start

To receive and process jSON I do:

server = WEBrick::HTTPServer.new(:Port => 3030, :DocumentRoot => '/')
server.mount_proc '/' do | req, res |
    Queue.new(req.body)
end

But I need this functionality combined, is there a way to do this with Webrick?


Solution

  • Yes, this is certainly possible with Webrick or any HTTP server. There will be two different HTTP actions depending on what the users wants to do, 1.) a GET request to serve the files or 2.) a POST request to process some JSON.

    Here's a simple example to show you how to do both:

    class Server < WEBrick::HTTPServlet::AbstractServlet
        def do_GET (request, response)
          puts "this is a get request"
        end
    
        def do_POST (request, response)
          puts "this is a post request who received #{request.body}"
        end
    end
    
    server = WEBrick::HTTPServer.new(:Port => 3030)
    
    server.mount "/", Server
    
    trap("INT") {
        server.shutdown
    }
    
    server.start
    

    Once that is running you can test this by doing the following in a separate terminal window:

    curl localhost:3030
    

    output:

    this is a get request
    localhost - - [23/Apr/2015:06:39:20 EDT] "GET / HTTP/1.1" 200 0
    - -> /
    

    To test the POST request:

    curl -d "{\"json\":\"payload\"}" localhost:3030
    

    output:

    this is a post request who received {"json":"payload"}
    localhost - - [23/Apr/2015:06:40:07 EDT] "POST / HTTP/1.1" 200 0
    - -> /