Last active
February 1, 2018 23:38
-
-
Save vfeskov/f68315e3bafaab2abf7867bc61697f5a to your computer and use it in GitHub Desktop.
Event machine
This file contains hidden or 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(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 |
This file contains hidden or 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 '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