WEBrick:记录POST数据

时间:2013-08-23 08:08:22

标签: ruby post webrick

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

我的代码是:

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

其中server只是一个WEBrick服务器。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

你有没有尝试过netcat?看看你是否有:

$ man nc

然后你可以启动这样的服务器:

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

如果我将带有'a = 10&amp; b = 20'数据的发布请求发送到http://locahost:8080,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