Skip to content

Instantly share code, notes, and snippets.

@vfeskov
Last active February 1, 2018 23:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vfeskov/4229d5076aa33fcab4aa19bdb4e833a5 to your computer and use it in GitHub Desktop.
Save vfeskov/4229d5076aa33fcab4aa19bdb4e833a5 to your computer and use it in GitHub Desktop.
New thread on each request
# frozen_string_literal: true
require 'redis'
class Handler
DB = Redis.new
def initialize(client, request, db)
@client = client
@request = request
end
def handle
method, full_path = @request.split(' ')
path = full_path.split('?').first
raise unless method == 'GET' && path =~ %r{^/[0-9]+$}
id = path[1..-1]
data = DB.get(id)
raise unless data
print 200, data
rescue
print 404, 'Not Found'
ensure
@client.close
end
def print(code, text)
@client.print "HTTP/1.1 #{code}\r\n"
@client.print "Content-Type: text/plain\r\n"
@client.print "Content-Length: #{text.length}\r\n"
@client.print "Connection: close"
@client.print "\r\n"
@client.print text
end
end
# frozen_string_literal: true
require 'socket'
require './handler'
port = ENV['PORT'] || 10_000
server = TCPServer.new port
loop do
Thread.fork(server.accept) do |client|
request = client.gets
Handler.new(client, request).handle
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment