Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a callback function on actix-web server start?

Currently my main function, where the server starts looks like this

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    let address = "0.0.0.0:3000";

    HttpServer::new(move || {
        let app_state = {...some state};
        App::new()
            .data(app_state)
            .wrap(middleware::Logger::default())
            .service(network_api::init_service())
    })    
    .bind(address)?
    .run()
    .await
}

Once the server starts, I want to run one (async) function, to make a request to another server, and that server should respond with another request to this server that just got up and running.

Not sure I see in the documentation anything mentioning a callback function that is run only once on server start.

For example maybe having it in run() function, like this:

run(|| {
  // server started now perform some request or whatever
  Client::new().post(&url).json(json_stuff).send().await
})

Edit I think I solved it, will post answer when I can answer my own question

like image 446
high incompetance Avatar asked Jun 14 '20 12:06

high incompetance


Video Answer


1 Answers

I have solved this by joining 2 async functions, created another async function

async fn another_func() -> Result<()> {
...
}

and have used future::join() like this

let server = HttpServer::new(move || {
        let app_state = {...some state};
        App::new()
            .data(app_state)
            .wrap(middleware::Logger::default())
            .service(network_api::init_service())
    })    
    .bind(address)?
    .run();

future::join(server, another_func()).await;

Ok(()

Of course if anyone has a better answer please post it

like image 136
high incompetance Avatar answered Sep 19 '22 06:09

high incompetance