Skip to content

Commit 9313eb6

Browse files
committed
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.
1 parent eb6eaf9 commit 9313eb6

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/client.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -501,13 +501,17 @@ impl Client {
501501

502502
/// Sets the base URL for this client. All request URLs will be relative to this URL.
503503
///
504+
/// Note: a trailing slash is significant.
505+
/// Without it, the last path component is considered to be a “file” name
506+
/// to be removed to get at the “directory” that is used as the base.
507+
///
504508
/// # Examples
505509
/// ```no_run
506510
/// # use http_types::Url;
507511
/// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
508512
/// let mut client = surf::client();
509-
/// client.set_base_url(Url::parse("http://example.com/api/v1")?);
510-
/// client.get("/posts.json").recv_json().await?; /// http://example.com/api/v1/posts.json
513+
/// client.set_base_url(Url::parse("http://example.com/api/v1/")?);
514+
/// client.get("posts.json").recv_json().await?; /// http://example.com/api/v1/posts.json
511515
/// # Ok(()) }) }
512516
/// ```
513517
pub fn set_base_url(&mut self, base: Url) {
@@ -522,3 +526,17 @@ impl Client {
522526
}
523527
}
524528
}
529+
530+
#[cfg(test)]
531+
mod client_tests {
532+
use super::Client;
533+
use crate::Url;
534+
535+
#[test]
536+
fn base_url() {
537+
let mut client = Client::new();
538+
client.set_base_url(Url::parse("http://example.com/api/v1/").unwrap());
539+
let url = client.url("posts.json");
540+
assert_eq!(url.as_str(), "http://example.com/api/v1/posts.json");
541+
}
542+
}

0 commit comments

Comments
 (0)