expression

Hyper service: call a handler directly

A Hyper service converts a request into an asynchronous response. Directly invoking it lets you test handler logic without opening sockets. This is not a test of HTTP serialization, middleware, or transport. In-memory fixture; no external connection. Expected stdout (not executed): 200 ready 404 missing Common mistake: Calling a direct service test an end-to-end network test.

Formal Syntax & Structure

rust syntaxrust
service_fn(|request| async move { ... }); service.call(request).await

Working Example

Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() {    use hyper::{Request, Response, StatusCode, service::{service_fn, Service}, body::Bytes};    use http_body_util::{Full, BodyExt};    let handler = service_fn(|req: Request<()>| async move {        let (status, msg) = if req.uri().path() == "/health" {            (StatusCode::OK, "ready")        } else { (StatusCode::NOT_FOUND, "missing") };        Ok::<_, std::convert::Infallible>(Response::builder().status(status)            .body(Full::new(Bytes::from_static(msg.as_bytes()))).unwrap())    });    for path in ["/health", "/other"] {        let response = handler.call(Request::builder().uri(path).body(()).unwrap()).await.unwrap();        let status = response.status().as_u16();        let data = response.into_body().collect().await.unwrap().to_bytes();        println!("{status} {}", std::str::from_utf8(&data).unwrap());    }}
Rust Reference