Skip to content

Instantly share code, notes, and snippets.

@naveed-fida
Created July 11, 2016 14:35
Show Gist options
  • Save naveed-fida/83e5c090c256e100a5dbab78695b8e88 to your computer and use it in GitHub Desktop.
Save naveed-fida/83e5c090c256e100a5dbab78695b8e88 to your computer and use it in GitHub Desktop.
Handling HTTP requests manually in ruby
require "socket"
def parse_request(request_line)
http_method, path_and_params, http_version = request_line.split(" ")
path, params = path_and_params.split("?")
params = (params || '').split("&").map {|p| p.split("=")}.to_h
[http_method, path, params]
end
server = TCPServer.new('localhost', 3003)
loop do
client = server.accept
request_line = client.gets
next unless request_line
next if request_line =~ /favicon/
puts request_line
http_method, path, params = parse_request(request_line)
client.puts "HTTP/1.0 200 OK"
client.puts 'Content-Type: text/html'
client.puts
client.puts "<html>"
client.puts "<body>"
client.puts '<pre>'
client.puts http_method
client.puts path
client.puts params
client.puts '</pre>'
client.puts '<h1>Counter</h1>'
number = params['number'].to_i
client.puts "<p>The current number is #{number}.</p>"
client.puts "<a href='?number=#{number + 1}'>Add One</a>"
client.puts "<a href='?number=#{number - 1}'>Subtract One</a>"
client.puts '</body>'
client.puts '</html>'
client.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment