I am using thin to receive HTTP POST requests, my server code is this:
http_server = proc do |env|
# Want to make response dependent on content
response = "Hello World!"
[200, {"Connection" => "close", "Content-Length" => response.bytesize.to_s}, [response]]
end
Setting a breakpoint, I can see that I have received the content-type (json), and content length, but can't see the actual content. How can I retrieve the content from the request for processing?
You need to use the rack.input
entry of the env
object. From the Rack Spec:
The input stream is an IO-like object which contains the raw HTTP POST data. When applicable, its external encoding must be “ASCII-8BIT” and it must be opened in binary mode, for Ruby 1.9 compatibility. The input stream must respond to
gets
,each
,read
andrewind
.
So you can call read
on it like this:
http_server = proc do |env|
json_string = env['rack.input'].read
json_string.force_encoding 'utf-8' # since the body has ASCII-8BIT encoding,
# but we know this is json, we can use
# force_encoding to get the right encoding
# parse json_string and do your stuff
response = "Hello World!"
[200, {"Connection" => "close", "Content-Length" => response.bytesize.to_s}, [response]]
end