http icon indicating copy to clipboard operation
http copied to clipboard

Base URI

Open sj26 opened this issue 7 years ago • 0 comments

I'm replacing a bunch of Faraday usage with the HTTP gem, it's fantastic. A common pattern I'm encountering is constructing a Faraday connection with a base URI, then doing requests using paths which are joined to the base URI.

client = Faraday.new(url: "https://api.github.com")
response = client.get("/search/code", q: "repo:httprb/http uri")
# => #<Faraday::Response:0xabc123 @on_complete_callbacks=[], @env=#<Faraday::Env @method=:get @url=#<URI::HTTPS https://api.github.com/search/code?q=repo%3Ahttprb%2Fhttp+uri> ...>

I notice that the HTTP gem does something simliar when using persistent connections:

client = HTTP.persistent("https://api.github.com")
response = http.get("/search/code", params: {q: "repo:httprb/http uri"})
# => #<HTTP::Request:0xabc123 @verb=:get, @uri=#<HTTP::URI:0xabc123 URI:https://api.github.com/search/code?q=...>, ...>

The Faraday version also works with path prefixes, so can use any URI as a base:

search_client = Faraday.new(url: "https://api.github.com/search/")
response = search_client.get("code", q: "repo:httprb/http uri")
# => #<Faraday::Response:0xabc123 @on_complete_callbacks=[], @env=#<Faraday::Env @method=:get @url=#<URI::HTTPS https://api.github.com/search/code?q=repo%3Ahttprb%2Fhttp+uri> ...>

The same does not work with HTTP:

client = HTTP.persistent("https://api.github.com/search/")
response = http.get("code", params: {q: "repo:httprb/http uri"})
# => HTTP::StateError (Persistence is enabled for https://api.github.com, but we got https://api.github.comcode)

This also requires using persistent connections, which may not always be desired.

Would a pull request be considered to add a base uri to options? Something like:

client = HTTP.uri("https://api.github.com/search/")
response =  client.get("code", params: {q: "repo:httprb/http uri"})
# => #<HTTP::Request:0xabc123 @verb=:get, @uri=#<HTTP::URI:0xabc123 URI:https://api.github.com/search/code?q=...>, ...>

which sets uri on HTTP::Options so that HTTP::Client#build_request via #make_request_uri looks for a uri on options and if present performs a Addressable::URI.join on the uri from options and the uri parameter?

sj26 avatar Dec 05 '18 00:12 sj26