To create a simple HTTP server with a PUT route in Ruby, we can use the WEBrick
module that comes bundled with Ruby.
main.rb420 chars24 lines
In the above code, we start by requiring the necessary modules WEBrick
and JSON
. We then create a new WEBrick::HTTPServer
instance on port 8000. Next, we mount a Proc
handler on the /data
route.
The handler checks if the HTTP method is PUT
. If it is, we parse the JSON payload using the JSON.parse
method and do something with the data. In this example, we simply return a success message. If the method is not PUT
, we return a 405 Method Not Allowed
response.
Finally, we set up a signal trap to listen for CTRL-C
SIGINT signals, which allows us to gracefully shutdown the server when it is interrupted. We then start the server by calling the start
method on the server
instance.
gistlibby LogSnag