Last active
February 1, 2018 23:36
-
-
Save vfeskov/4229d5076aa33fcab4aa19bdb4e833a5 to your computer and use it in GitHub Desktop.
New thread on each request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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