Skip to content

Instantly share code, notes, and snippets.

@vfeskov
Last active February 1, 2018 23:38
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/f68315e3bafaab2abf7867bc61697f5a to your computer and use it in GitHub Desktop.
Save vfeskov/f68315e3bafaab2abf7867bc61697f5a to your computer and use it in GitHub Desktop.
Event machine
# frozen_string_literal: true
require 'redis'
class Handler
DB = Redis.new
def initialize(headers, client)
@headers = headers
@client = client
end
def handle
request = @headers.first
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_connection_after_writing
end
def print(code, text)
@client.send_data "HTTP/1.1 #{code}\r\n"
@client.send_data "Content-Type: text/plain\r\n"
@client.send_data "Content-Length: #{text.length}\r\n"
@client.send_data "Connection: close"
@client.send_data "\r\n"
@client.send_data text
end
end
# frozen_string_literal: true
require 'eventmachine'
require './handler'
class Server < EM::P::HeaderAndContentProtocol
def receive_request(headers, content)
Handler.new(headers, self).handle
end
end
port = ENV['PORT'] || 10_000
EM.run { EM.start_server 'localhost', port, Server }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment