Skip to content

Instantly share code, notes, and snippets.

@tmiller
Created June 26, 2012 18:40
Show Gist options
  • Save tmiller/2997842 to your computer and use it in GitHub Desktop.
Save tmiller/2997842 to your computer and use it in GitHub Desktop.
Small server
require 'socket'
require 'thread'
server = TCPServer.open(8080)
HEADER = <<-EOH
HTTP/1.1 200 OK
Content-Type: text/html; charset=ISO-8859-1
EOH
def respond_with(filename)
HEADER + File.read(filename) if File.exists?(filename)
end
loop do
Thread.start(server.accept) do |client|
request = client.gets.split("\r\n").first.split(' ')
case request[1]
when '/'
client.puts respond_with('./index.html')
else
filename = "./#{request[1]}"
filename << '.html' unless filename =~ /\.\w{3,4}$/
client.puts respond_with(filename)
end
client.close
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment