[][src]Module surf::middleware

Middleware types

Examples

use futures::future::BoxFuture;
use surf::middleware::{Next, Middleware, Request, Response, HttpClient};
use std::time;

/// Log each request's duration
#[derive(Debug)]
pub struct Logger;

impl<C: HttpClient> Middleware<C> for Logger {
    fn handle<'a>(
        &'a self,
        req: Request,
        client: C,
        next: Next<'a, C>,
    ) -> BoxFuture<'a, Result<Response, surf::Exception>> {
        Box::pin(async move {
            println!("sending request to {}", req.uri());
            let now = time::Instant::now();
            let res = next.run(req, client).await?;
            println!("request completed ({:?})", now.elapsed());
            Ok(res)
        })
    }
}

Middleware can also be instantiated using a free function thanks to some convenient trait implementations.

use futures::future::BoxFuture;
use surf::middleware::{Next, Middleware, Request, Response, HttpClient};
use std::time;

fn logger<'a, C: HttpClient>(req: Request, client: C, next: Next<'a, C>) -> BoxFuture<'a, Result<Response, surf::Exception>> {
    Box::pin(async move {
        println!("sending request to {}", req.uri());
        let now = time::Instant::now();
        let res = next.run(req, client).await?;
        println!("request completed ({:?})", now.elapsed());
        Ok(res)
    })
}

Modules

logger

Logging middleware.

Structs

Body

The raw body of an http request or response.

Next

The remainder of a middleware chain, including the endpoint.

Traits

HttpClient

[unstable] An abstract HTTP client.

Middleware

Middleware that wraps around remaining middleware chain.

Type Definitions

Request

An HTTP Request type with a streaming body.

Response

An HTTP Response type with a streaming body.