如何在 ruby 中的 Faraday 客户端每次重试时更改 Auth header?
How to change the Auth header in every retry in Faraday client in ruby?
我的 Rails 应用程序中定义了一个 HTTP get 方法,类似这样。我想知道如何在每次重试时更新 headers 中的新 OAuth 令牌?
def configure(service_base_uri, auth_header)
Faraday.new(service_base_uri) do |faraday|
faraday.headers['Authorization'] = auth_header
faraday.request :retry, max: 5, interval: 0.05
faraday.adapter Faraday.default_adapter
end
end
def get(service_base_uri, path, error_message, params = {})
auth_header = auth_token_generator(service_base_uri, path)
connection = configure(service_base_uri, auth_header, headers)
response = connection.get(parsed_uri.path, params)
return JSON.parse(response.body)
end
def auth_token_generator(service_base_uri, path)
# Some code
end
Faraday::Request::Retry
class 允许一个名为 retry_block
的参数。
retry_block - block that is executed after every retry.
Request environment, middleware options, current number of retries and the exception is passed to the block as parameters.
由于环境被传递到块中,您可以使用它来修改下一个请求的headers:
Faraday.new(...) do |faraday|
faraday.headers['Authorization'] = auth_header
faraday.request :retry, ...,
retry_block: proc { |env, opts, retries, exception|
env.request_headers['Authorization'] = "Hello #{retries}"
}
end
我的 Rails 应用程序中定义了一个 HTTP get 方法,类似这样。我想知道如何在每次重试时更新 headers 中的新 OAuth 令牌?
def configure(service_base_uri, auth_header)
Faraday.new(service_base_uri) do |faraday|
faraday.headers['Authorization'] = auth_header
faraday.request :retry, max: 5, interval: 0.05
faraday.adapter Faraday.default_adapter
end
end
def get(service_base_uri, path, error_message, params = {})
auth_header = auth_token_generator(service_base_uri, path)
connection = configure(service_base_uri, auth_header, headers)
response = connection.get(parsed_uri.path, params)
return JSON.parse(response.body)
end
def auth_token_generator(service_base_uri, path)
# Some code
end
Faraday::Request::Retry
class 允许一个名为 retry_block
的参数。
retry_block - block that is executed after every retry. Request environment, middleware options, current number of retries and the exception is passed to the block as parameters.
由于环境被传递到块中,您可以使用它来修改下一个请求的headers:
Faraday.new(...) do |faraday|
faraday.headers['Authorization'] = auth_header
faraday.request :retry, ...,
retry_block: proc { |env, opts, retries, exception|
env.request_headers['Authorization'] = "Hello #{retries}"
}
end