Skip to content

Instantly share code, notes, and snippets.

@toretore
Last active Jan 3, 2016
Embed
What would you like to do?
require 'socket'
class Page
attr_reader :body, :method, :path
def initialize(m, p, b)
@body, @method, @path = b, m, p
end
end
class Server
attr_reader :pages
def initialize
@pages = []
end
def add_page(p)
pages << p
end
alias << add_page
def page_for(m, p)
pages.find do |page|
page.method == m && page.path == p
end
end
def response_for(m, p)
if page = page_for(m, p)
[page, "HTTP/1.1 200 OK\r\nContent-Length: #{page.body.bytesize}\r\n\r\n#{page.body}"]
else
[nil, "HTTP/1.1 404 Not Found\r\nContent-Length: 14\r\n\r\nPage not found"]
end
end
end
server = Server.new
server << Page.new('GET', '/hello', 'Hello World')
stop = Page.new('DELETE', '/world', 'Goodbye World')
server << stop
sock = TCPServer.new('0.0.0.0', 1337)
while client = sock.accept
method, path = client.gets.split(' ')[0,2]
page, response = server.response_for(method, path)
client.write response
break if page == stop
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment