create a http server with a post route in ruby

To create an HTTP server with a POST route in Ruby, you can use the built-in WEBrick library.

Here's an example code snippet that creates a server with a /post route, which accepts POST HTTP requests and returns a response with the received data:

main.rb
require 'webrick'

server = WEBrick::HTTPServer.new(Port: 8000)

server.mount_proc '/post' do |req, res|
  if req.request_method == 'POST'
    res.status = 200
    res.body = "Received POST request with data: #{req.body}"
  else
    res.status = 405
  end
end

server.start
274 chars
15 lines

In this example, we use the mount_proc method to define the /post route. The code inside the block determines what happens when a request is received at that URL.

We check if the request method is POST, and if it is, we set the response status to 200 and return a message that includes the request body.

If the request method is not POST, we set the response status to 405 to indicate that the request is not allowed.

To start the server, we call the start method on the server object. The server will listen on port 8000 by default (unless we specify a different Port option when creating the server).

gistlibby LogSnag