class LocationRedirector
A client wrapper which transparently handles redirects to a given maximum number of hops.
The default implementation will only follow relative locations (i.e. those without a scheme) and will switch to GET if the original request was not a GET.
The best reference for these semantics is defined by the Fetch specification.
Redirect using GET | Permanent | Temporary |
---|---|---|
Allowed | 301 | 302 |
Preserve original method | 308 | 307 |
For the specific details of the redirect handling, see:
- https://datatracker.ietf.org/doc/html/rfc7231#section-6-4-2 301 Moved Permanently.
- https://datatracker.ietf.org/doc/html/rfc7231#section-6-4-3 302 Found.
- <https://datatracker.ietf.org/doc/html/rfc7538 308 Permanent Redirect.
- https://datatracker.ietf.org/doc/html/rfc7231#section-6-4-7 307 Temporary Redirect.
Nested
Definitions
PROHIBITED_GET_HEADERS = [...]
Header keys which should be deleted when changing a request from a POST to a GET as defined by https://fetch.spec.whatwg.org/#request-body-header-name.
Implementation
PROHIBITED_GET_HEADERS = [
"content-encoding",
"content-language",
"content-location",
"content-type",
]
def initialize(app, maximum_hops = 3)
maximum_hops is the max number of redirects. Set to 0 to allow 1 request with no redirects.
Implementation
def initialize(app, maximum_hops = 3)
super(app)
@maximum_hops = maximum_hops
end
attr :maximum_hops
The maximum number of hops which will limit the number of redirects until an error is thrown.
def handle_redirect(request, location)
Handle a redirect to a relative location.
Signature
-
parameter
request
Protocol::HTTP::Request
The original request, which you can modify if you want to handle the redirect.
-
parameter
location
String
The relative location to redirect to.
-
returns
Boolean
True if the redirect was handled, false if it was not.
Implementation
def handle_redirect(request, location)
uri = URI.parse(location)
if uri.absolute?
return false
end
# Update the path of the request:
request.path = Reference[request.path] + location
# Follow the redirect:
return true
end