lib/itamae/resource/http_request.rb in itamae-1.9.2 vs lib/itamae/resource/http_request.rb in itamae-1.9.3
- old
+ new
@@ -1,28 +1,46 @@
require 'itamae'
require 'uri'
-require 'net/http'
+require 'net/https'
module Itamae
module Resource
class HttpRequest < File
- UrlNotFoundError = Class.new(StandardError)
+ RedirectLimitExceeded = Class.new(StandardError)
define_attribute :action, default: :get
define_attribute :headers, type: Hash, default: {}
define_attribute :message, type: String, default: ""
+ define_attribute :redirect_limit, type: Integer, default: 10
define_attribute :url, type: String, required: true
def pre_action
uri = URI.parse(attributes.url)
- http = Net::HTTP.new(uri.host, uri.port)
- http.use_ssl = true if uri.scheme == "https"
+ response = nil
+ redirects_followed = 0
- case attributes.action
- when :delete, :get, :options
- response = http.method(attributes.action).call(uri.request_uri, attributes.headers)
- when :post, :put
- response = http.method(attributes.action).call(uri.request_uri, attributes.message, attributes.headers)
+ loop do
+ http = Net::HTTP.new(uri.host, uri.port)
+ http.use_ssl = true if uri.scheme == "https"
+
+ case attributes.action
+ when :delete, :get, :options
+ response = http.method(attributes.action).call(uri.request_uri, attributes.headers)
+ when :post, :put
+ response = http.method(attributes.action).call(uri.request_uri, attributes.message, attributes.headers)
+ end
+
+ if response.kind_of?(Net::HTTPRedirection)
+ if redirects_followed < attributes.redirect_limit
+ uri = URI.parse(response["location"])
+ redirects_followed += 1
+ Itamae.logger.debug "Following redirect #{redirects_followed}/#{attributes.redirect_limit}"
+ else
+ raise RedirectLimitExceeded
+ end
+ else
+ break
+ end
end
attributes.content = response.body
super