To create an HTTP server in Ruby, you can use the built-in WEBrick
library. Here's an example that sets up a server and reads the request body as form-urlencoded:
main.rb611 chars24 lines
In this example, we define a class MyServer
that inherits from WEBrick::HTTPServlet::AbstractServlet
. We then define a do_POST
method that handles POST requests. Inside this method, we parse the form-urlencoded request body using URI.decode_www_form(request.body)
. This returns an array of key-value pairs, which we convert to a hash using to_h
.
We then print the parameters to the console using puts
, set up the response headers and body, and send the response using response.status = 200
, response['Content-Type'] = 'text/plain'
, response.body = 'Received POST request'
, and response.send_response
.
Finally, we set up the server to listen on port 8000 by creating a new WEBrick::HTTPServer
object and calling server.mount('/', MyServer)
to mount our MyServer
class on the root URL. We also add a signal handler to shut down the server gracefully when we receive an interrupt signal, and start the server using server.start
.
gistlibby LogSnag