http-rs / surf

Fast and friendly HTTP client framework for async Rust
https://docs.rs/surf
Apache License 2.0
1.46k stars 120 forks source link

Rename Client::middleware to Client::with #207

Closed Fishrock123 closed 4 years ago

Fishrock123 commented 4 years ago

The Surf counterpart to https://github.com/http-rs/tide/issues/665

This issue as written assumes https://github.com/http-rs/surf/pull/194 being merged.


From https://github.com/http-rs/tide/issues/665:

Initially the Server::middleware method was chosen because Server::use isn't possible as it's a reserved keyword. The idea was to resemble Express's choice of naming. So instead of using a verb I chose to just name it what it is in the expectation that we could later find a suitable verb.

As I was doing some work with the tracing crate today I noticed they use the with method to compose various Layers. This is much the same as our middleware, and actually fits well. The with function name in the stdlib is also canonically used to add a function that the item is passed through first.

So I'd like to propose we rename Client:middleware to Client::with, bringing it in line with Tide post-https://github.com/http-rs/tide/issues/665.

Example

With this change:

let req = surf::get("https://httpbin.org/get");
let client = surf::client()
    .with(MyMiddleware::new());
let res = client.send(req).await?;

Without this change:

let req = surf::get("https://httpbin.org/get");
let client = surf::client()
    .middleware(MyMiddleware::new());
let res = client.send(req).await?;

Future

The expectation is that we'll eventually have async closures, which would allow us to author this with anonymous middleware from closures, which would make with an even more accurate nomer.

let req = surf::get("https://httpbin.org/get");
let client = surf::client().with(async |req, next| {
    println!("outgoing {} method", req.method());
    next().await
});
let res = client.send(req).await?;