Skip to content

Commit eed67ad

Browse files
Add before_routing for Reverse Proxy plugins (#1252)
* Add `before_routing` for Reverse Proxy plugins * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent be771d4 commit eed67ad

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

proxy/http/server/plugin.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@
1313
from abc import ABC, abstractmethod
1414
from typing import TYPE_CHECKING, Any, Dict, List, Tuple, Union, Optional
1515

16-
from proxy.http.url import Url
1716
from ..parser import HttpParser
17+
from ...http.url import Url
1818
from ..responses import NOT_FOUND_RESPONSE_PKT, okResponse
1919
from ..websocket import WebsocketFrame
2020
from ..connection import HttpClientConnection
@@ -161,6 +161,12 @@ def routes(self) -> List[Union[str, Tuple[str, List[bytes]]]]:
161161
must return the url to serve."""
162162
raise NotImplementedError() # pragma: no cover
163163

164+
def before_routing(self, request: HttpParser) -> Optional[HttpParser]:
165+
"""Plugins can modify request, return response, close connection.
166+
167+
If None is returned, request will be dropped and closed."""
168+
return request # pragma: no cover
169+
164170
def handle_route(self, request: HttpParser, pattern: RePattern) -> Url:
165171
"""Implement this method if you have configured dynamic routes."""
166172
pass

proxy/http/server/reverse.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ def __init__(self, *args: Any, **kwargs: Any):
4646
self.plugins.append(plugin)
4747

4848
def handle_upstream_data(self, raw: memoryview) -> None:
49+
# TODO: Parse response and implement plugin hook per parsed response object
50+
# This will give plugins a chance to modify the responses before dispatching to client
4951
self.client.queue(raw)
5052

5153
def routes(self) -> List[Tuple[int, str]]:
@@ -57,6 +59,14 @@ def routes(self) -> List[Tuple[int, str]]:
5759
return r
5860

5961
def handle_request(self, request: HttpParser) -> None:
62+
# before_routing
63+
for plugin in self.plugins:
64+
r = plugin.before_routing(request)
65+
if r is None:
66+
raise HttpProtocolException('before_routing closed connection')
67+
request = r
68+
69+
# routes
6070
for plugin in self.plugins:
6171
for route in plugin.routes():
6272
if isinstance(route, tuple):
@@ -73,6 +83,7 @@ def handle_request(self, request: HttpParser) -> None:
7383
break
7484
else:
7585
raise ValueError('Invalid route')
86+
7687
assert self.choice and self.choice.hostname
7788
port = self.choice.port or \
7889
DEFAULT_HTTP_PORT \

0 commit comments

Comments
 (0)