【问题标题】:How to get the content from an HTTP POST request received in thin?如何从接收到的 HTTP POST 请求中获取内容?
【发布时间】:2013-08-17 18:18:30
【问题描述】:

我使用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),还有内容长度,但是看不到实际的内容。如何从处理请求中检索内容?

【问题讨论】:

    标签: ruby rack thin


    【解决方案1】:

    您需要使用env 对象的rack.input 条目。来自Rack Spec

    输入流是一个类似 IO 的对象,其中包含原始 HTTP POST 数据。适用时,其外部编码必须为“ASCII-8BIT”,并且必须以二进制模式打开,以兼容 Ruby 1.9。输入流必须响应getseachreadrewind

    所以你可以这样调用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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-15
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多