我使用thin来接收HTTP POST请求,我的服务器代码是这样的:
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
设置断点,我可以看到我已经收到了content-type(json)和内容长度,但看不到实际内容。如何从请求中检索内容进行处理?
最佳答案
您需要使用env
对象的rack.input
条目。来自 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
.
所以你可以像这样调用read
:
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
关于ruby - 如何从 Thin 中收到的 HTTP POST 请求中获取内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18254726/