ruby - 如何从 Thin 中收到的 HTTP POST 请求中获取内容?

标签 ruby rack thin

我使用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 and 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

关于ruby - 如何从 Thin 中收到的 HTTP POST 请求中获取内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18254726/

相关文章:

mysql - 需要将数组转换为整数以用于 Rails API 中的 MySQL 查询

ruby - rails 3 中的日期减法?

ruby - 如何指定内存缓存服务器到 Rack::Session::Memcache?

heroku - 重定向 URL 以在 Sinatra 中添加尾部斜杠

ruby-on-rails - Capistrano + Thin + nginx 不允许用户使用 sudo howto?

ruby - 如何在同一端口上提供 Cramp::Websocket 和普通 Rack 应用程序?

ruby - 获取加载时添加的内容

ruby - 如何在 Ruby 中进行高级字符串比较?

ruby - Sinatra/Rack session.fetch 产生意外结果

ruby - 如何在默认端口上开始精简?