简体   繁体   中英

faraday timeout on a simple get

Is there a way to add timeout options in this simple get method?

I am using Faraday 3.3.

Faraday.get(url)

After searching around, I can only apply timeout options after I initiate a connection first, then apply timeout options. Or there's a simple way?

This is what I am doing right now:

conn = Faraday.new
response = conn.get do |req|
  req.url url
  req.options.timeout = 2 # 2 seconds
end

Try this one:

conn = Faraday.new do |conn|
  conn.options.timeout = 20
end
response = conn.get(url)

UPD: After I had reviewed gem sources, I found out that there's no way do it like you want.

With get method you can set only url, request params and headers . But to specify timeout, you have to access @options of Faraday::Connection instance. And you can do this by using attr_reader :options

conn = Faraday::Connection.new
conn.options.timeout = 20

Or on initialization of Faraday::Connection instance:

Faraday::Connection.new(nil, request: { timeout: 20 })

Or when it copies connection parameters to request parameter and yields request back :

Faraday::Connection.new.get(url) { |request| request.options.timeout = 20 }

I had the same problem and I ended up doing something like this so I can more easily stub the code in testing:

    def self.get(url, params: {}, headers: {}, timeout: 2)
      conn = Faraday.new(
        params: params,
        headers: headers
      ) do |conn|
        conn.options.timeout = timeout
      end

      conn.get(url)
    end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM