Ruby Queue
I wanted to build a simple queue that could accept HTTP requests to enqueue and dequeue, to keep things simple enough to post via a curl command. With Ruby being my go-to language for hobby projects, I wrote this:
require 'sinatra'
$queue = []
get '/' do
if $queue.length == 0
status 404
content_type('text/plain')
return 'EMPTY'
end
content_type('application/json')
$queue.shift
end
post '/' do
if request.content_type != 'application/json'
status 500
content_type('text/plain')
return 'ERROR'
end
$queue.push request.body.read
content_type('text/plain')
'OK'
end
The POST handler takes in the body of a request with HTTP request content type “application/json” and appends it to an array.
The GET handler removes the item from the queue and returns it as the body of the HTTP response content type “application/json”.
If the array is empty, the GET handler returns a 404 with an EMPTY message sent with HTTP response content type “text/plain”.
To run the above, save it within main.rb
, then gem install sinatra
and ruby main.rb
. By default, Sinatra listens on the localhost port 4567. To change this, set :bind, '0.0.0.0'
and set :port, 8080
in the Ruby code. If you are using this for anything more than throw-away code or a prototype, make the bind IP and port configurable, add authentication, and even TLS/SSL.