merge readme changes

This commit is contained in:
rick 2011-12-28 13:44:22 -07:00
commit a928ee53ad
6 changed files with 220 additions and 89 deletions

152
README.md
View File

@ -5,7 +5,9 @@ Modular HTTP client library that uses middleware. Heavily inspired by Rack.
[gemnasium]: https://gemnasium.com/technoweenie/faraday [gemnasium]: https://gemnasium.com/technoweenie/faraday
## <a name="usage"></a>Usage ## <a name="usage"></a>Usage
conn = Faraday.new(:url => 'http://sushi.com') do |builder|
```ruby
conn = Faraday.new(:url => 'http://sushi.com') do |builder|
builder.use Faraday::Request::UrlEncoded # convert request params as "www-form-urlencoded" builder.use Faraday::Request::UrlEncoded # convert request params as "www-form-urlencoded"
builder.use Faraday::Request::JSON # encode request params as json builder.use Faraday::Request::JSON # encode request params as json
builder.use Faraday::Response::Logger # log the request to STDOUT builder.use Faraday::Response::Logger # log the request to STDOUT
@ -16,50 +18,70 @@ Modular HTTP client library that uses middleware. Heavily inspired by Rack.
builder.request :json builder.request :json
builder.response :logger builder.response :logger
builder.adapter :net_http builder.adapter :net_http
end end
## GET ## ## GET ##
response = conn.get '/nigiri/sake.json' # GET http://sushi.com/nigiri/sake.json response = conn.get '/nigiri/sake.json' # GET http://sushi.com/nigiri/sake.json
response.body response.body
conn.get '/nigiri', 'X-Awesome' => true # custom request header conn.get '/nigiri', 'X-Awesome' => true # custom request header
conn.get do |req| # GET http://sushi.com/search?page=2&limit=100 conn.get do |req| # GET http://sushi.com/search?page=2&limit=100
req.url '/search', :page => 2 req.url '/search', :page => 2
req.params['limit'] = 100 req.params['limit'] = 100
end end
## POST ## ## POST ##
conn.post '/nigiri', { :name => 'Maguro' } # POST "name=maguro" to http://sushi.com/nigiri conn.post '/nigiri', { :name => 'Maguro' } # POST "name=maguro" to http://sushi.com/nigiri
# post payload as JSON instead of "www-form-urlencoded" encoding: # post payload as JSON instead of "www-form-urlencoded" encoding:
conn.post '/nigiri', payload, 'Content-Type' => 'application/json' conn.post '/nigiri', payload, 'Content-Type' => 'application/json'
# a more verbose way: # a more verbose way:
conn.post do |req| conn.post do |req|
req.url '/nigiri' req.url '/nigiri'
req.headers['Content-Type'] = 'application/json' req.headers['Content-Type'] = 'application/json'
req.body = { :name => 'Unagi' } req.body = { :name => 'Unagi' }
end end
## Options ##
conn.get do |req|
req.url '/search'
req.options = {
:timeout => 5, # open/read timeout Integer in seconds
:open_timeout => 2, # read timeout Integer in seconds
:proxy => {
:uri => "http://example.org/", # proxy server URI
:user => "me", # proxy server username
:password => "test123" # proxy server password
}
}
end
```
If you're ready to roll with just the bare minimum: If you're ready to roll with just the bare minimum:
# default stack (net/http), no extra middleware: ```ruby
response = Faraday.get 'http://sushi.com/nigiri/sake.json' # default stack (net/http), no extra middleware:
response = Faraday.get 'http://sushi.com/nigiri/sake.json'
```
## Advanced middleware usage ## Advanced middleware usage
The order in which middleware is stacked is important. Like with Rack, the first middleware on the list wraps all others, while the last middleware is the innermost one, so that's usually the adapter. The order in which middleware is stacked is important. Like with Rack, the first middleware on the list wraps all others, while the last middleware is the innermost one, so that's usually the adapter.
conn = Faraday.new(:url => 'http://sushi.com') do |builder| ```ruby
conn = Faraday.new(:url => 'http://sushi.com') do |builder|
# POST/PUT params encoders: # POST/PUT params encoders:
builder.request :multipart builder.request :multipart
builder.request :url_encoded builder.request :url_encoded
builder.request :json builder.request :json
builder.adapter :net_http builder.adapter :net_http
end end
```
This request middleware setup affects POST/PUT requests in the following way: This request middleware setup affects POST/PUT requests in the following way:
@ -71,79 +93,87 @@ Because "UrlEncoded" is higher on the stack than JSON encoder, it will get to pr
Examples: Examples:
payload = { :name => 'Maguro' } ```ruby
payload = { :name => 'Maguro' }
# post payload as JSON instead of urlencoded: # post payload as JSON instead of urlencoded:
conn.post '/nigiri', payload, 'Content-Type' => 'application/json' conn.post '/nigiri', payload, 'Content-Type' => 'application/json'
# uploading a file: # uploading a file:
payload = { :profile_pic => Faraday::UploadIO.new('avatar.jpg', 'image/jpeg') } payload = { :profile_pic => Faraday::UploadIO.new('avatar.jpg', 'image/jpeg') }
# "Multipart" middleware detects files and encodes with "multipart/form-data": # "Multipart" middleware detects files and encodes with "multipart/form-data":
conn.put '/profile', payload conn.put '/profile', payload
```
## Writing middleware ## Writing middleware
Middleware are classes that respond to `call()`. They wrap the request/response cycle. Middleware are classes that respond to `call()`. They wrap the request/response cycle.
def call(env) ```ruby
def call(env)
# do something with the request # do something with the request
@app.call(env).on_complete do @app.call(env).on_complete do
# do something with the response # do something with the response
end end
end end
```
It's important to do all processing of the response only in the `on_complete` block. This enables middleware to work in parallel mode where requests are asynchronous. It's important to do all processing of the response only in the `on_complete` block. This enables middleware to work in parallel mode where requests are asynchronous.
The `env` is a hash with symbol keys that contains info about the request and, later, response. Some keys are: The `env` is a hash with symbol keys that contains info about the request and, later, response. Some keys are:
# request phase ```
:method - :get, :post, ... # request phase
:url - URI for the current request; also contains GET parameters :method - :get, :post, ...
:body - POST parameters for :post/:put requests :url - URI for the current request; also contains GET parameters
:request_headers :body - POST parameters for :post/:put requests
:request_headers
# response phase # response phase
:status - HTTP response status code, such as 200 :status - HTTP response status code, such as 200
:body - the response body :body - the response body
:response_headers :response_headers
```
## <a name="testing"></a>Testing ## <a name="testing"></a>Testing
# It's possible to define stubbed request outside a test adapter block.
stubs = Faraday::Adapter::Test::Stubs.new do |stub|
stub.get('/tamago') { [200, {}, 'egg'] }
end
# You can pass stubbed request to the test adapter or define them in a block ```ruby
# or a combination of the two. # It's possible to define stubbed request outside a test adapter block.
test = Faraday.new do |builder| stubs = Faraday::Adapter::Test::Stubs.new do |stub|
stub.get('/tamago') { [200, {}, 'egg'] }
end
# You can pass stubbed request to the test adapter or define them in a block
# or a combination of the two.
test = Faraday.new do |builder|
builder.adapter :test, stubs do |stub| builder.adapter :test, stubs do |stub|
stub.get('/ebi') {[ 200, {}, 'shrimp' ]} stub.get('/ebi') {[ 200, {}, 'shrimp' ]}
end end
end end
# It's also possible to stub additional requests after the connection has # It's also possible to stub additional requests after the connection has
# been initialized. This is useful for testing. # been initialized. This is useful for testing.
stubs.get('/uni') {[ 200, {}, 'urchin' ]} stubs.get('/uni') {[ 200, {}, 'urchin' ]}
resp = test.get '/tamago' resp = test.get '/tamago'
resp.body # => 'egg' resp.body # => 'egg'
resp = test.get '/ebi' resp = test.get '/ebi'
resp.body # => 'shrimp' resp.body # => 'shrimp'
resp = test.get '/uni' resp = test.get '/uni'
resp.body # => 'urchin' resp.body # => 'urchin'
resp = test.get '/else' #=> raises "no such stub" error resp = test.get '/else' #=> raises "no such stub" error
# If you like, you can treat your stubs as mocks by verifying that all of # If you like, you can treat your stubs as mocks by verifying that all of
# the stubbed calls were made. NOTE that this feature is still fairly # the stubbed calls were made. NOTE that this feature is still fairly
# experimental: It will not verify the order or count of any stub, only that # experimental: It will not verify the order or count of any stub, only that
# it was called once during the course of the test. # it was called once during the course of the test.
stubs.verify_stubbed_calls stubs.verify_stubbed_calls
```
## <a name="todo"></a>TODO ## <a name="todo"></a>TODO
* support streaming requests/responses * support streaming requests/responses
* better stubbing API * better stubbing API
* Support timeouts
* Add curb, em-http, fast_http * Add curb, em-http, fast_http
## <a name="pulls"></a>Note on Patches/Pull Requests ## <a name="pulls"></a>Note on Patches/Pull Requests

View File

@ -15,12 +15,16 @@ module Faraday
autoload_all 'faraday/request', autoload_all 'faraday/request',
:JSON => 'json', :JSON => 'json',
:UrlEncoded => 'url_encoded', :UrlEncoded => 'url_encoded',
:Multipart => 'multipart' :Multipart => 'multipart',
:Retry => 'retry',
:Timeout => 'timeout'
register_lookup_modules \ register_lookup_modules \
:json => :JSON, :json => :JSON,
:url_encoded => :UrlEncoded, :url_encoded => :UrlEncoded,
:multipart => :Multipart :multipart => :Multipart,
:retry => :Retry,
:timeout => :Timeout
attr_reader :method attr_reader :method

View File

@ -0,0 +1,21 @@
module Faraday
class Request::Retry < Faraday::Middleware
def initialize(app, retries = 2)
@retries = retries
super(app)
end
def call(env)
retries = @retries
begin
@app.call(env)
rescue StandardError, Timeout::Error => e
if retries > 0
retries -= 1
retry
end
raise
end
end
end
end

View File

@ -0,0 +1,31 @@
module Faraday
class Request::Timeout < Faraday::Middleware
dependency "timeout"
def initialize(app, timeout = 2)
self.class.dependency "system_timer" if ruby18?
@timeout = timeout
super(app)
end
def call(env)
method =
if ruby18? && self.class.loaded?
SystemTimer.method(:timeout_after)
else
Timeout.method(:timeout)
end
method.call(@timeout) do
@app.call(env)
end
end
private
def ruby18?
@ruby18 ||= RUBY_VERSION =~ /^1\.8/
end
end
end

View File

@ -0,0 +1,25 @@
require File.expand_path(File.join(File.dirname(__FILE__), "..", "helper"))
module Middleware
class RetryTest < Faraday::TestCase
def setup
@stubs = Faraday::Adapter::Test::Stubs.new
@conn = Faraday.new do |b|
b.request :retry, 2
b.adapter :test, @stubs
end
end
def test_retries
times_called = 0
@stubs.post("/echo") do
times_called += 1
raise "Error occurred"
end
@conn.post("/echo") rescue nil
assert_equal times_called, 3
end
end
end

View File

@ -0,0 +1,20 @@
require File.expand_path(File.join(File.dirname(__FILE__), "..", "helper"))
module Middleware
class TimeoutTest < Faraday::TestCase
def setup
@conn = Faraday.new do |b|
b.request :timeout, 0.01 # 10 ms
b.adapter :test do |stub|
stub.post("/echo") do |env|
sleep(1)
end
end
end
end
def test_request_times_out
assert_raise(TimeoutError) { @conn.post("/echo") }
end
end
end