-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Enhance URLResolverMiddleware to support host-based path resolu…
…tion
- Loading branch information
1 parent
181b65b
commit fd16f6d
Showing
1 changed file
with
23 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
|
||
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}' | ||
else: | ||
resolved_path = f'/{current_host}{request.path}' | ||
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 | ||