Skip to content

Instantly share code, notes, and snippets.

@le0pard
Created September 22, 2026 14:36
Show Gist options
  • Select an option

  • Save le0pard/5a514b89c5c507706abdff64d5e6f350 to your computer and use it in GitHub Desktop.

Select an option

Save le0pard/5a514b89c5c507706abdff64d5e6f350 to your computer and use it in GitHub Desktop.
Debug http request web server
require 'socket'
server = TCPServer.new(8080)
puts "Debug HTTP server running on port 8080..."
loop do
# Threading prevents a single hanging/broken request from locking up the server
Thread.start(server.accept) do |socket|
begin
puts "\n" + "="*50
puts "New Connection from #{socket.peeraddr[2]}:#{socket.peeraddr[1]}"
puts "="*50
# 1. Read Request Line
request_line = socket.gets
# Using .inspect is crucial for debugging broken requests
# because it reveals hidden carriage returns (\r) and newlines (\n)
puts "Request Line: #{request_line.inspect}"
content_length = 0
# 2. Read Headers
while (line = socket.gets) && (line != "\r\n")
puts "Header: #{line.inspect}"
# Extract Content-Length (case-insensitive) to know body size
if line =~ /^content-length:\s*(\d+)/i
content_length = $1.to_i
end
end
puts "-" * 50
# 3. Read the Body
if content_length > 0
puts "Expected Body Size: #{content_length} bytes"
# Read exact number of bytes.
# (socket.read without arguments would hang indefinitely until the client closes)
body = socket.read(content_length)
puts "Body payload:\n#{body.inspect}"
else
# 4. Fallback for completely broken requests
# If there's no Content-Length, check if they sent stray body data anyway.
begin
# Wait up to 0.5 seconds for unexpected data
if IO.select([socket], nil, nil, 0.5)
stray_data = socket.recv_nonblock(4096)
puts "Stray/Unannounced Body Data (No Content-Length provided):\n#{stray_data.inspect}" unless stray_data.empty?
end
rescue IO::WaitReadable, EOFError
# No stray data found, which is normal.
end
end
# 5. Send Response
socket.print "HTTP/1.1 200 OK\r\n"
socket.print "Content-Type: text/plain\r\n"
socket.print "Connection: close\r\n\r\n"
socket.print "Request received and debugged!"
puts "="*50
rescue => e
puts "\n[!] Error handling request: #{e.class} - #{e.message}"
puts e.backtrace.first(3).join("\n")
ensure
socket.close
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment