【问题标题】:WEBrick: log POST dataWEBrick:记录 POST 数据
【发布时间】:2013-08-23 08:08:21
【问题描述】:

我正在运行一个简单的 WEBrick 服务器来调试 POST 数据。我想将 POST 数据输出到日志中。

我的代码是:

server.mount_proc '/' do |req, res|
    res.body = "Web server response:\n"
    # Output POST data here...
end

server 只是一个 WEBrick 服务器。

有什么建议吗?

【问题讨论】:

    标签: ruby post webrick


    【解决方案1】:

    使用req.body 访问原始帖子数据。

    server.mount_proc '/' do |req, res|
        res.body = "Web server response:\n"
        p req.body # <---
    end
    

    如果您想要解析数据(作为哈希),请改用req.query

    更新

    自定义:AccessLog:

    require 'webrick'
    
    log = [[ $stderr, WEBrick::AccessLog::COMMON_LOG_FORMAT + ' POST=%{body}n']]
    
    server = WEBrick::HTTPServer.new :Port => 9000, :AccessLog => log
    server.mount_proc '/' do |req, res|
        req.attributes['body'] = req.body
        res.body = "Web server response:\n"
    end
    server.start
    

    【讨论】:

      【解决方案2】:

      你试过netcat吗?看看你有没有这样做:

      $ man nc
      

      然后你可以像这样启动一个服务器:

      $ nc -l 8080    (-l act as a server, listening on port 8080)
      (hangs)
      

      如果我向http://locahost:8080 发送带有数据'a=10&b=20' 的发布请求,netcat 输出:

      $ nc -l 8080    
      POST / HTTP/1.1
      Host: localhost:8080
      User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:23.0) Gecko/20100101 Firefox/23.0
      Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
      Accept-Language: null
      Accept-Encoding: gzip, deflate
      DNT: 1
      Content-Length: 9
      Content-Type: text/plain; charset=UTF-8
      Connection: keep-alive
      Pragma: no-cache
      Cache-Control: no-cache
      
      a=10&b=20
      

      【讨论】:

      • 在 Mac OS X 上,nc -l 8080 对我不起作用。我不得不改用nc -lp 8080 (结合lp 听起来好像它不应该工作但似乎为我解决了问题)。
      • 嗯...我使用的是 OSX 10.6.8,手册页说:-l It is an error to use this option in conjunction with the -p option,和:-p It is an error to use this option in conjunction with the -l option。当我同时尝试这两个选项时,netcat 会显示一条使用消息而不是启动。不使用 -p 会发生什么?
      猜你喜欢
      • 2013-05-10
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 2011-11-04
      • 1970-01-01
      • 2010-11-02
      • 2011-04-12
      • 1970-01-01
      相关资源
      最近更新 更多