Refactored locale middleware function