How to specify a read timeout for a Net::HTTP::Post.new request in Ruby 2

后端 未结 5 1114
生来不讨喜
生来不讨喜 2021-01-01 13:26

I have a post happening to a rails application from a ruby script. The script creates a variable request as

request = Net::HTTP::Post.new(url.path)
         


        
5条回答
  •  太阳男子
    2021-01-01 14:01

    I catch both OpenTimeout and ReadTimeout and it's work. test in Ruby:2.6.5

    def ping(host, port)
        begin
            url = URI.parse("http://#{host}:#{port}/ping")
            req = Net::HTTP::Get.new(url.to_s)
    
            # setting both OpenTimeout and ReadTimeout
            res = Net::HTTP.start(url.host, url.port, :open_timeout => 3, :read_timeout => 3) {|http|
              http.request(req)
            }
    
            if JSON.parse(res.body)["ok"]
              # return true
              STDERR.puts "#{host}:#{port} is reachable"
            else
              STDERR.puts "#{host}:#{port} is NOT reachable"
            end
        rescue Net::ReadTimeout => exception
            STDERR.puts "#{host}:#{port} is NOT reachable (ReadTimeout)"
        rescue Net::OpenTimeout => exception
            STDERR.puts "#{host}:#{port} is NOT reachable (OpenTimeout)"
        end
    
    end
    
    ping("#{ENV['FIRST_HOST']}", 2345)
    ping("#{ENV['SECOND_HOST']}", 2345)
    

提交回复
热议问题