Skip to content

Instantly share code, notes, and snippets.

@halferty
Created January 6, 2017 11:36
Show Gist options
  • Save halferty/e8ea0e98f49e4cf426086658947c0868 to your computer and use it in GitHub Desktop.
Save halferty/e8ea0e98f49e4cf426086658947c0868 to your computer and use it in GitHub Desktop.
Simple pure-ruby standard-library-only HTTP server
#!/usr/bin/env ruby
require 'socket'
require 'json'
server = TCPServer.new '0.0.0.0', 8765
loop do
socket = server.accept
data = ""
while (line = socket.gets) && line != "\r\n"
data += line
end
type, path = data.split(/ /)[0..1]
content_length = data =~ /Content-Length: (\d+)/ ? $1.to_i : 0
body = socket.read content_length if content_length > 0
puts ({ type: type, path: path, body: body }).inspect
respond = -> (code, body, headers = []) {
names = { 200 => "OK", 404 => "Not Found" }
socket.puts "HTTP/1.1 #{code} #{names[code]}\r\n"
headers.each { |k, v| socket.puts "#{k}: #{v}\r\n" }
socket.puts "Content-Length: #{body.size}\r\n\r\n#{body}"
}
handlers = [
["GET", /\A\/posts\/\d+\/comments, -> () { respond.call(200,
[{ title: "asdf", author: "guy blahdude" }].to_json + "\n",
{ "Content-Type" => "application/json" }
)}]
]
handler = handlers.find { |h| type == h[0] && path =~ h[1] }
handler ? handler[2].call : respond.call(404, "No idea, man\n")
socket.close
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment