Skip to content

Commit

Permalink
feat: Enhance URLResolverMiddleware to support host-based path resolu…
Browse files Browse the repository at this point in the history
…tion
  • Loading branch information
abdullai-t committed Dec 5, 2024
1 parent 181b65b commit fd16f6d
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions src/api/middlewares/url_resolver_middleware.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
from django.http import HttpResponse
from django.urls import resolve, Resolver404
from _main_.hosts import host_patterns


class URLResolverMiddleware:
def __init__(self, get_response):
self.get_response = get_response
self.host_map = {host.regex: host for host in host_patterns}

def __call__(self, request):
resolved_path = self._resolve_path(request)
if resolved_path is None:
return HttpResponse("This endpoint does not exist.", status=404)

Check warning on line 14 in src/api/middlewares/url_resolver_middleware.py

View check run for this annotation

Codecov / codecov/patch

src/api/middlewares/url_resolver_middleware.py#L14

Added line #L14 was not covered by tests

request.path_info = resolved_path
return self.get_response(request)

def _resolve_path(self, request):
try:
resolve(request.path)
current_host = request.get_host().split('.')[0]
if current_host in self.host_map:
if request.path == '/':
resolved_path = f'/{current_host}'

Check warning on line 24 in src/api/middlewares/url_resolver_middleware.py

View check run for this annotation

Codecov / codecov/patch

src/api/middlewares/url_resolver_middleware.py#L23-L24

Added lines #L23 - L24 were not covered by tests
else:
resolved_path = f'/{current_host}{request.path}'

Check warning on line 26 in src/api/middlewares/url_resolver_middleware.py

View check run for this annotation

Codecov / codecov/patch

src/api/middlewares/url_resolver_middleware.py#L26

Added line #L26 was not covered by tests
else:
resolved_path = request.path

resolve(resolved_path)
return resolved_path
except Resolver404:
return HttpResponse("This endpoint does not exist.", status=404)

return self.get_response(request)
return None

Check warning on line 33 in src/api/middlewares/url_resolver_middleware.py

View check run for this annotation

Codecov / codecov/patch

src/api/middlewares/url_resolver_middleware.py#L33

Added line #L33 was not covered by tests

0 comments on commit fd16f6d

Please sign in to comment.