繁体   English   中英

从Ruby TCPSocket上的HTTP连接中提取uri参数

[英]Extract uri parameters from a HTTP connection on a Ruby TCPSocket

我在这里的第一个问题...所以要温柔: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服务器,以便接收几个参数,并希望避免使用gems和/或Rack之类的完整HTTP包装器/帮助器。

不用说...但是在此先感谢。

如果您想看到一个非常小的服务器,这里是一个。 它恰好处理两个参数,并将字符串放入数组中。 您需要做更多的工作来处理可变数量的参数。

有关服务器代码的完整说明,请访问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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM