Refactor middleware pattern matching

I replaced the deeply nested code and if/else if/else blocks with an
array of handler functions and a processing loop.