Skip to content

There is no way to pass data to the new Server connection service in Hyper 1 #3463

@calavera

Description

@calavera

Version
Hyper 1

Description

In Hyper 0.14, you could create a service that passed data to the connection service. This example in the old documentation explained how:

use std::convert::Infallible;
use std::net::SocketAddr;
use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn};
use hyper::server::conn::AddrStream;

#[derive(Clone)]
struct AppContext {
    // Whatever data your application needs can go here
}

async fn handle(
    context: AppContext,
    addr: SocketAddr,
    req: Request<Body>
) -> Result<Response<Body>, Infallible> {
    Ok(Response::new(Body::from("Hello World")))
}

#[tokio::main]
async fn main() {
    let context = AppContext {
        // ...
    };

    // A `MakeService` that produces a `Service` to handle each connection.
    let make_service = make_service_fn(move |conn: &AddrStream| {
        // We have to clone the context to share it with each invocation of
        // `make_service`. If your data doesn't implement `Clone` consider using
        // an `std::sync::Arc`.
        let context = context.clone();

        // You can grab the address of the incoming connection like so.
        let addr = conn.remote_addr();

        // Create a `Service` for responding to the request.
        let service = service_fn(move |req| {
            handle(context.clone(), addr, req)
        });

        // Return the service to hyper.
        async move { Ok::<_, Infallible>(service) }
    });

    // Run the server like above...
    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));

    let server = Server::bind(&addr).serve(make_service);

    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }

It's the last example in the old documentation: https://docs.rs/hyper/0.14.27/hyper/server/index.html#examples

This seems impossible to achieve now because serve_connection takes a service that receives Request<ReqBody>.

I expected to find an example or explanation on how to accomplish this with the new stable version, but it seems just gone.

How can I accomplish this in Hyper 1?

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: bug. Something is wrong. This is bad!

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions