在Ruby中的自制服务器中解析POST请求主体 [英] Parse body of POST reqest in self-made server in Ruby
问题描述
我正在编写模拟Ruby服务器来测试API组件.我发送带有正文的POST请求,我希望我的模拟服务器返回该POST请求的正文.目前,我有以下代码:
I am writing mock Ruby servers to test components of API. I send a POST request with a body, and I'd like my mock server to return a body of that POST request. Currently i have this code:
require 'socket'
webserver = TCPServer.new('127.0.0.1', 7125)
loop do
session = webserver.accept
session.print "HTTP/1.1 200/OK\r\nContent-type:text/html\r\n\r\n"
request = session.gets
session.puts request
session.close
end
正文为FOO
的POST请求返回的响应中,正文仅包含POST / HTTP/1.1
如何解决?
A POST request with body FOO
returns a response with body that contains only POST / HTTP/1.1
How to fix it?
推荐答案
编写自己的HTTP服务器确实会使您陷入麻烦,因为该规范虽然表面上很简单,但仍有许多细微的细微差别可能会使您绊倒.在这种情况下,您正在使用gets
读一行,而忽略了大部分提交.您将必须通过读取并正确解码所发布的数据来解决此问题.
Writing your own HTTP server is really going to get you into trouble because the specification, while superficially simple, has a number of subtle nuances that can trip you up. In this case, you're reading one line with gets
and ignoring the bulk of the submission. You're going to have to address that by reading in and properly decoding the posted data.
对于界面熟悉的内容,您可以从 Net :: HTTP :: Server .
For something with a familiar interface you might start with Net::HTTP::Server instead.
这篇关于在Ruby中的自制服务器中解析POST请求主体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!