Function warp::service

source · []
pub fn service<F>(filter: F) -> FilteredService<F> where
    F: Filter,
    <F::Future as TryFuture>::Ok: Reply,
    <F::Future as TryFuture>::Error: IsReject, 
Expand description

Convert a Filter into a Service.

Filters are normally what APIs are built on in warp. However, it can be useful to convert a Filter into a Service, such as if further customizing a hyper::Service, or if wanting to make use of the greater Tower set of middleware.

Example

Running a warp::Filter on a regular hyper::Server:

use std::convert::Infallible;
use warp::Filter;

// Our Filter...
let route = warp::any().map(|| "Hello From Warp!");

// Convert it into a `Service`...
let svc = warp::service(route);

// Typical hyper setup...
let make_svc = hyper::service::make_service_fn(move |_| async move {
    Ok::<_, Infallible>(svc)
});

hyper::Server::bind(&([127, 0, 0, 1], 3030).into())
    .serve(make_svc)
    .await?;
Examples found in repository?
examples/autoreload.rs (line 24)
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
async fn main() {
    // Match any request and return hello world!
    let routes = warp::any().map(|| "Hello, World!");

    // hyper let's us build a server from a TcpListener (which will be
    // useful shortly). Thus, we'll need to convert our `warp::Filter` into
    // a `hyper::service::MakeService` for use with a `hyper::server::Server`.
    let svc = warp::service(routes);

    let make_svc = hyper::service::make_service_fn(|_: _| {
        // the clone is there because not all warp filters impl Copy
        let svc = svc.clone();
        async move { Ok::<_, Infallible>(svc) }
    });

    let mut listenfd = ListenFd::from_env();
    // if listenfd doesn't take a TcpListener (i.e. we're not running via
    // the command above), we fall back to explicitly binding to a given
    // host:port.
    let server = if let Some(l) = listenfd.take_tcp_listener(0).unwrap() {
        Server::from_tcp(l).unwrap()
    } else {
        Server::bind(&([127, 0, 0, 1], 3030).into())
    };

    server.serve(make_svc).await.unwrap();
}