[][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, http_types::Error>> {
        Box::pin(async move {
            println!("sending request to {}", req.url());
            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, http_types::Error>> {
    Box::pin(async move {
        println!("sending request to {}", req.url());
        let now = time::Instant::now();
        let res = next.run(req, client).await?;
        println!("request completed ({:?})", now.elapsed());
        Ok(res)
    })
}

Modules

logger

Logging middleware.

Structs

Next

The remainder of a middleware chain, including the endpoint.

Traits

HttpClient

An abstract HTTP client.

Middleware

Middleware that wraps around remaining middleware chain.

Type Definitions

Body

The raw body of an http request or response.

Request

An HTTP Request type with a streaming body.

Response

An HTTP Response type with a streaming body.