How to share Stuct data as state using hyper server

how to share this test data accross hyper.
for example:

strcut Router { name:String, data:HashMap}

let mut c_router = Router::new();
let s2 = Arc::new(c_router);
let make_svc = make_service_fn(|| async {
Ok::<
, GenericError>(service_fn(|req| handle_url(s2.clone(), req)))
});
let server = Server::bind(&addr).serve(make_svc);

if i use Arc::clone, then it will shows clone dont live long enough as lifetime issues.

the example from hyper is only share a usize data, which impl copy, it is easy to share.
but how to share things like this?

my conclusion is that dont mislead by the cargo check info , the problem it infers maybe not the key problem. you need to try to analyze the key problem by your self.

I happen to have an example of this lying around. Here you go:

use std::convert::Infallible;
use std::net::SocketAddr;
use std::sync::Arc;

use hyper::server::conn::AddrStream;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Server, Request, Response, Body};

type BoxError = Box<dyn std::error::Error + Send + Sync>;

struct SharedData {
    foo: u32,
}

#[tokio::main]
async fn main() {
    let addr = SocketAddr::from(([127, 0, 0, 1], 8100));

    let shared = Arc::new(SharedData {
        foo: 10,
    });

    // This is the connection handler.
    let make_service = make_service_fn(move |client: &AddrStream| {
        let ip = client.remote_addr();
        let shared = shared.clone();
        async move {
            // This is the request handler.
            Ok::<_, Infallible>(service_fn(move |req| {
                let shared = shared.clone();
                handle_request(ip, req, shared)
            }))
        }
    });
    let server = Server::bind(&addr).serve(make_service);

    println!("Starting server on http://localhost:8100/");
    if let Err(e) = server.await {
        eprintln!("server error: {}", e);
    }
}

async fn handle_request(
    ip: SocketAddr,
    req: Request<Body>,
    shared: Arc<SharedData>,
) -> Result<Response<Body>, BoxError> {
    Ok(Response::new(Body::from(
        format!(
            "Hi {}. You want {} and foo is {}.",
            ip,
            req.uri(),
            shared.foo,
        )
    )))
}
4 Likes

i tried these ways, it still shows that the clone have life time issues.

or maybe your examples uses u32 which impl Copy too.

can you try some more complex struct , such as String or HashMap?

Notice that there is no #[derive(Copy)] on my struct. The SharedData struct does not implement Copy, and works with String fields too.

thanks. my cargo check always said about lifetime issues, and i trust it.

but i copied your code , more errors come out , when i fix these ,my origin code clone lifetime issue is gone, it is really wired.

maybe there is a cache ?

If you paste my example into the playground like this, it compiles as-is with no changes. You can try cargo clean if you think it is a cache issue, but I don't think that is usually the case.

Perhaps you only copied some of my code and left the rest to be your own code, which left out some important detail from my example?

yeah, maybe.
i think i'm mislead by the cargo check info.
struggling fight for lifetime issue, but actually is the usage problem.
i will check more info.
thanks a lot

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.