我的第一个问题......所以要温柔:D
我有以下代码:
server = TCPServer.new('localhost', 8080)
loop do
socket = server.accept
# Do something with the URL parameters
response = "Hello world";
socket.print response
socket.close
end
关键是我希望能够检索是否已在HTTP请求的URL中发送任何参数。
示例:
根据此请求:
curl http://localhost:8080/?id=1&content=test
我希望能够检索到这样的内容:
{id => "1", content => "test"}
我一直在寻找CGI :: Parse [1]或类似的解决方案,但我还没有找到从TCPSocket中提取数据的方法。
[1] http://www.ruby-doc.org/stdlib-1.9.3/libdoc/cgi/rdoc/CGI.html#method-c-parse
仅供参考:我需要有一个最小的http服务器,以便接收一些参数,并希望避免使用宝石和/或像Rack这样的完整HTTP包装器/帮助器。
毋庸置疑......但提前谢谢。
答案 0 :(得分:3)
如果你想看到一个非常小的服务器,这里就是一个。它只处理两个参数,并将字符串放在一个数组中。您需要做更多工作来处理可变数量的参数。
https://practicingruby.com/articles/implementing-an-http-file-server对服务器代码有更全面的解释。
require "socket"
server = TCPServer.new('localhost', 8080)
loop do
socket = server.accept
request = socket.gets
# Here is the first line of the request. There are others.
# Your parsing code will need to figure out which are
# the ones you need, and extract what you want. Rack will do
# this for you and give you everything in a nice standard form.
paramstring = request.split('?')[1] # chop off the verb
paramstring = paramstring.split(' ')[0] # chop off the HTTP version
paramarray = paramstring.split('&') # only handles two parameters
# Do something with the URL parameters which are in the parameter array
# Build a response!
# you need to include the Content-Type and Content-Length headers
# to let the client know the size and type of data
# contained in the response. Note that HTTP is whitespace
# sensitive and expects each header line to end with CRLF (i.e. "\r\n")
response = "Hello world!"
socket.print "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"Content-Length: #{response.bytesize}\r\n" +
"Connection: close\r\n"
# Print a blank line to separate the header from the response body,
# as required by the protocol.
socket.print "\r\n"
socket.print response
socket.close
end