我使用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
设置断点,我可以看到我收到了内容类型(json)和内容长度,但看不到实际内容。如何从请求中检索内容?
答案 0 :(得分:2)
您需要使用rack.input
对象的env
条目。来自Rack Spec:
输入流是一个类似IO的对象,它包含原始HTTP POST数据。适用时,其外部编码必须为“ASCII-8BIT”,并且必须以二进制模式打开,以实现Ruby 1.9兼容性。输入流必须回复
gets
,each
,read
和rewind
。
所以你可以这样打电话给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