Created
March 27, 2018 20:51
-
-
Save jbarber/f439fddb0c1fe1c093712d19432a69c2 to your computer and use it in GitHub Desktop.
Prototypical Ruby event machine based webserver for serving context over unix domain sockets
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
$ echo '{"foo": "bar"}' | curl --unix-socket /tmp/foo.bar http://www.google.com/echo -d @- | |
{"message":"{\"foo\": \"bar\"}"} | |
$ curl --unix-socket /tmp/foo.bar http://www.google.com/popper | |
{"message":"🎉"} |
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 'json' | |
require 'eventmachine' | |
require 'em-http-server' | |
require 'byebug' | |
class HTTPHandler < EM::HttpServer::Server | |
ROUTES = [ | |
['/echo', :echo], | |
['/popper', :popper], | |
].freeze | |
def ok(body) | |
respond({message: body}, 200) | |
end | |
def error(body) | |
respond({error: body}, 400) | |
end | |
def respond(body, status) | |
response = EM::DelegatedHttpResponse.new(self) | |
response.content_type 'application/json' | |
response.status = status | |
response.content = body.to_json | |
response.send_response | |
end | |
def echo | |
ok(@http_content) | |
end | |
def popper | |
ok('🎉') | |
end | |
def default | |
error("no handler found for #{@http_request_uri}") | |
end | |
def process_http_request | |
_, handle = ROUTES.find do |matcher, _| | |
@http_request_uri.match(matcher, 0) { true } | |
end | |
if handle | |
self.send(handle) | |
else | |
default | |
end | |
end | |
def http_request_errback(e) | |
STDERR.puts(e.backtrace) | |
error('Something went wrong') | |
end | |
end | |
EM::run do | |
EM::start_unix_domain_server('/tmp/foo.bar', HTTPHandler) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment