简体   繁体   中英

Extract uri parameters from a HTTP connection on a Ruby TCPSocket

My first question here... so be gentle :D

I have the following code:

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

The point is that I want to be able to retrieve if any parameters have been sent in URL of the HTTP request.

Example:

From this request:

curl http://localhost:8080/?id=1&content=test    

I want to be able to retrieve something like this:

{id => "1", content => "test"}    

I've been looking for CGI::Parse[1] or similar solutions but I haven't found a way to extract that data from a TCPSocket.

[1] http://www.ruby-doc.org/stdlib-1.9.3/libdoc/cgi/rdoc/CGI.html#method-c-parse

FYI: My need is to have a minimal http server in order to receive a couple of parameters and wanted to avoid the use of gems and/or full HTTP wrappers/helpers like Rack.

Needless to say... but thanks in advance.

If you want to see a very minimal server, here is one. It handles exactly two parameters, and puts the strings in an array. You'll need to do more to handle variable numbers of parameters.

There is a fuller explanation of the server code at 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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