From 9313eb689be4e31ead910272ce5a181e780206d2 Mon Sep 17 00:00:00 2001 From: Jeffrey Crocker Date: Tue, 13 Oct 2020 13:36:02 -0400 Subject: [PATCH] Fix client base_url documentation The client base URL example sets the base URL to "http://example.com/api/v1", which is then joined with a URI of "/posts.json". This had two bugs: - The base url did not end with '/', and so 'v1' was treated as a file path, and dropped from the result. This lead to resulting URLs like: "http://example.com/api/posts.json", without the 'v1'. - the joined URI (/posts.json) begins with a '/', and so it was treated as an absolute path from the domain. This lead to resulting URLs like: "http://example.com/posts.json", without the '/api/v1'. This commit fixes both of these bugs in the example. It also adds a note to the documentation (copied from the URL crate) about the importance of the ending '/'. One test was added to ensure the base_url behavior. --- src/client.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/client.rs b/src/client.rs index 05c8c75..465e262 100644 --- a/src/client.rs +++ b/src/client.rs @@ -501,13 +501,17 @@ impl Client { /// Sets the base URL for this client. All request URLs will be relative to this URL. /// + /// Note: a trailing slash is significant. + /// Without it, the last path component is considered to be a “file” name + /// to be removed to get at the “directory” that is used as the base. + /// /// # Examples /// ```no_run /// # use http_types::Url; /// # fn main() -> http_types::Result<()> { async_std::task::block_on(async { /// let mut client = surf::client(); - /// client.set_base_url(Url::parse("http://example.com/api/v1")?); - /// client.get("/posts.json").recv_json().await?; /// http://example.com/api/v1/posts.json + /// client.set_base_url(Url::parse("http://example.com/api/v1/")?); + /// client.get("posts.json").recv_json().await?; /// http://example.com/api/v1/posts.json /// # Ok(()) }) } /// ``` pub fn set_base_url(&mut self, base: Url) { @@ -522,3 +526,17 @@ impl Client { } } } + +#[cfg(test)] +mod client_tests { + use super::Client; + use crate::Url; + + #[test] + fn base_url() { + let mut client = Client::new(); + client.set_base_url(Url::parse("http://example.com/api/v1/").unwrap()); + let url = client.url("posts.json"); + assert_eq!(url.as_str(), "http://example.com/api/v1/posts.json"); + } +}