44import re
55import typing
66from http .client import HTTP_PORT , HTTPS_PORT
7- from typing import List , Tuple
7+ from typing import List , Optional , Tuple
88
99from starlette .middleware .cors import CORSMiddleware as _CORSMiddleware
1010from starlette .types import ASGIApp , Receive , Scope , Send
@@ -95,12 +95,13 @@ def _get_forwarded_url_parts(self, scope: Scope) -> Tuple[str]:
9595 domain = header_host_parts [0 ]
9696 port = None
9797
98+ port_str = None # make sure it is defined in all paths since we access it later
99+
98100 if forwarded := self ._get_header_value_by_name (scope , "forwarded" ):
99101 for proxy in forwarded .split ("," ):
100- if (proto_expr := _PROTO_HEADER_REGEX .search (proxy )) and (
101- host_expr := _HOST_HEADER_REGEX .search (proxy )
102- ):
102+ if proto_expr := _PROTO_HEADER_REGEX .search (proxy ):
103103 proto = proto_expr .group ("proto" )
104+ if host_expr := _HOST_HEADER_REGEX .search (proxy ):
104105 domain = host_expr .group ("host" )
105106 port_str = host_expr .group ("port" ) # None if not present in the match
106107
@@ -115,8 +116,8 @@ def _get_forwarded_url_parts(self, scope: Scope) -> Tuple[str]:
115116 return (proto , domain , port )
116117
117118 def _get_header_value_by_name (
118- self , scope : Scope , header_name : str , default_value : str = None
119- ) -> str :
119+ self , scope : Scope , header_name : str , default_value : Optional [ str ] = None
120+ ) -> Optional [ str ] :
120121 headers = scope ["headers" ]
121122 candidates = [
122123 value .decode () for key , value in headers if key .decode () == header_name
0 commit comments