Ruby: Following redirects with the http gem ("httprb")

Posted 6 days ago. Visible to the public.

When making requests using the http gem you might want to automatically follow redirects to get the desired response. This is supported but not the default behavior.

You can do so by using the .follow method.
This follows redirects for the following status codes: 300, 301, 302, 303, 307, 308

response = HTTP.get('https://www.example.com/redirect')
response.status # => 302
response.uri.to_s # => "https://www.example.com/redirect"

response = HTTP.follow.get('https://www.example.com/redirect')
response.status # => 200
response.uri.to_s # => "https://www.example.com/this-is-where-i-actually-want-to-be"

Limiting maximum amount of redirects

The .follow method also allows setting a maximum allowed amount of hops by settings the :max_hops option.The default is 5.
curl for example uses 30 as the default Show archive.org snapshot .

# would raise an error if there are more than 3 redirects
response = HTTP.follow(max_hops: 3).get('https://www.example.com/redirect') 

Endless redirect loops

These are automatically checked for and an error will be raised if this occurs.

For more information see the httprb docs Show archive.org snapshot .

Maximilian Berger
Last edit
3 days ago
Felix Eschey
License
Source code in this card is licensed under the MIT License.
Posted by Maximilian Berger to makandra dev (2024-05-13 09:17)