How to use the environment argument in both lazy_static and main scopes?

I set the function of the environment parameter in lazy_static!, but I also need to use it in fn main() now, set data_service_port to environment variable, how can I accomplish this?

 lazy_static! {

    static ref SESSION: Session = {
        let args: Vec<String> = env::args().collect();
        let ip_addr = &args[1];
        let num = &args[2];
        let t_num = &args[3];
        let port_num: u16 = num.parse::<u16>().unwrap();
        let thread_num: u32 = t_num.parse::<u32>().unwrap();

        Cluster::default()
            .set_contact_points(ip_addr)
                .expect("Failed to set_contact_points")
            .set_port(port_num)
                .expect("Failed to set_port")
            .set_num_threads_io(thread_num)
                .expect("Failed to set_num_threads_io")
            .set_retry_policy(RetryPolicy::default_new())
            .connect()
                .expect("Failed to connect to the cluster")
    };
}


fn main() {

    HttpServer::new(|| {
        App::new()
            .wrap(Logger::default())
            .service(web::scope("/data/1")
                .wrap(NormalizePath)
                .route("/{deviceid}/{epoch}/{feature}/{filter}", web::get().to(filter_data_web)))
            .route("/health", web::to(|| HttpResponse::Ok().body("ok")))
    })
        .workers(4)
        .bind(data_service_port)
        .unwrap()
        .run();

}

Instead of lazy_static, you could use once_cell and configure it at startup.

1 Like