Skip to content

Commit

Permalink
[ruby/open-uri] Set default for max_redirects and add exception class
Browse files Browse the repository at this point in the history
  • Loading branch information
ankane authored and matzbot committed Dec 7, 2023
1 parent d97479f commit 41c00bc
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
7 changes: 5 additions & 2 deletions lib/open-uri.rb
Expand Up @@ -108,7 +108,7 @@ module OpenURI
:ftp_active_mode => false,
:redirect => true,
:encoding => nil,
:max_redirects => nil,
:max_redirects => 64,
}

def OpenURI.check_options(options) # :nodoc:
Expand Down Expand Up @@ -240,7 +240,7 @@ def OpenURI.open_loop(uri, options) # :nodoc:
uri = redirect
raise "HTTP redirection loop: #{uri}" if uri_set.include? uri.to_s
uri_set[uri.to_s] = true
raise "Too many redirects" if max_redirects && uri_set.size > max_redirects
raise TooManyRedirects.new("Too many redirects", buf.io) if max_redirects && uri_set.size > max_redirects
else
break
end
Expand Down Expand Up @@ -395,6 +395,9 @@ def initialize(message, io, uri)
attr_reader :uri
end

class TooManyRedirects < HTTPError
end

class Buffer # :nodoc: all
def initialize
@io = StringIO.new
Expand Down
2 changes: 1 addition & 1 deletion test/open-uri/test_open-uri.rb
Expand Up @@ -572,7 +572,7 @@ def test_max_redirects_too_many
srv.mount_proc("/r1/") {|req, res| res.status = 301; res["location"] = "#{url}/r2"; res.body = "r1" }
srv.mount_proc("/r2/") {|req, res| res.status = 301; res["location"] = "#{url}/r3"; res.body = "r2" }
srv.mount_proc("/r3/") {|req, res| res.body = "r3" }
exc = assert_raise(RuntimeError) { URI.open("#{url}/r1/", max_redirects: 1) {} }
exc = assert_raise(OpenURI::TooManyRedirects) { URI.open("#{url}/r1/", max_redirects: 1) {} }
assert_equal("Too many redirects", exc.message)
}
end
Expand Down

0 comments on commit 41c00bc

Please sign in to comment.