diff options
author | azul <azul@riseup.net> | 2016-08-29 10:19:22 +0000 |
---|---|---|
committer | azul <azul@riseup.net> | 2016-08-29 10:19:22 +0000 |
commit | 6e2d31e3f7c515f65d92533bcdb035438461a00c (patch) | |
tree | 4efa7445db3a0521a14d75e626d64f85434a3ea5 /lib/nickserver/dispatcher.rb | |
parent | c134e0940a44ba3fb3f0f8ee86faa8053a9e0b44 (diff) | |
parent | 0784391a21b75ca52892e992a614b0f927ade00e (diff) |
Merge branch 'refactor/request-handling' into 'master'
refactor: restructure the way we handle requests to make it more consistent.
Requests are handled at a lot of different ways in different styles right now.
Let's make this more consistent and flexible to add email lookup at other leap providers.
See merge request !2
Diffstat (limited to 'lib/nickserver/dispatcher.rb')
-rw-r--r-- | lib/nickserver/dispatcher.rb | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/lib/nickserver/dispatcher.rb b/lib/nickserver/dispatcher.rb new file mode 100644 index 0000000..8bcfd05 --- /dev/null +++ b/lib/nickserver/dispatcher.rb @@ -0,0 +1,65 @@ +# +# Dispatcher +# +# Dispatch a request so it get's handled by the correct handler. +# +# The dispatcher hands a request to one handler after the other until one of +# them responds. +# +# This is similar to the Chain of Responsibility patter but we iterate over the +# 'handler_chain' array instead of a linked list. +# +# To change the order of handlers or add other handlers change the array in the +# handler_chain function. +# + +require 'nickserver/request' +require 'nickserver/request_handlers/invalid_email_handler' +require 'nickserver/request_handlers/local_email_handler' +require 'nickserver/request_handlers/email_handler' +require 'nickserver/request_handlers/fingerprint_handler' + +module Nickserver + class Dispatcher + + def initialize(responder) + @responder = responder + end + + def respond_to(params, headers) + request = Nickserver::Request.new params, headers + response = handle request + send_response response.status, response.content + end + + protected + + def handle(request) + handler_chain.each do |handler| + response = handler.call request + return response if response + end + rescue RuntimeError => exc + puts "Error: #{exc}" + puts exc.backtrace + ErrorResponse.new(exc.to_s) + end + + def handler_chain + [ + RequestHandlers::InvalidEmailHandler.new, + RequestHandlers::LocalEmailHandler.new, + RequestHandlers::EmailHandler.new, + RequestHandlers::FingerprintHandler.new, + Proc.new { Nickserver::Response.new(404, "Not Found\n") } + ] + end + + def send_response(status = 200, content = '') + responder.respond status, content + end + + attr_reader :responder + + end +end |