Skip to content

Instantly share code, notes, and snippets.

@jbarber
Last active March 27, 2018 20:51
Show Gist options
  • Save jbarber/377917d32f5dbf94a4c96da5a6271c98 to your computer and use it in GitHub Desktop.
Save jbarber/377917d32f5dbf94a4c96da5a6271c98 to your computer and use it in GitHub Desktop.
Prototypical Ruby event machine based webserver for serving context over unix domain sockets
$ 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":"🎉"}
# 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