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.rb274 chars15 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