factor out ugly use code to apply_middlewares function

Signed-off-by: Niv Sardi <xaiki@evilgiggle.com>