Skip to content

Instantly share code, notes, and snippets.

@Najaf
Last active August 29, 2015 14:01
Show Gist options
  • Save Najaf/3791874a83eafe3cada1 to your computer and use it in GitHub Desktop.
Save Najaf/3791874a83eafe3cada1 to your computer and use it in GitHub Desktop.
#! /usr/bin/env ruby
require 'socket'
def log(source, message)
time = Time.now.strftime("%Y-%m-%d %H:%M:%S")
puts "[%s] %s => %s" % [time, source, message]
end
# Class representing HTTP Requests
Request = Struct.new(:method, :uri, :version, :headers) do
def self.parse(client)
# parse the request line
method, uri, version = client.readline.split
Request.new(method, uri, version, {}).tap do |r|
# read the headers
until (header_line = client.readline).strip == '' do
header, value = header_line.split(':').map { |s| s.strip }
r.headers[header] = value
end
end
end
end
server = TCPServer.new ARGV.first.to_i
loop do
client = server.accept
info = client.remote_address
source = "%s:%s" % [info.ip_address, info.ip_port]
log source, "Connection established"
request = Request.parse(client)
log source, "Method = %s | URI = %s | Version = %s" % [request.method, request.uri, request.version]
log source, "Headers = %s" % request.headers.inspect
client.close
log source, "Connection terminated"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment