rustrust-rocket

How to run rocket code from another file?


I can't launch my rocket code from my main file main.rs. I want my main code to run in parallel with the rocket code and remain in the background until I close the process in the terminal.

src\bin\web_page.rs

extern crate rocket;
use rocket::*;

#[get("/<identifier>")]
fn test(identifier: &str) -> String {
    format!("Your identifier is {}", identifier)
}

#[launch]
pub fn rocket() -> _ {
    println!("Rocket started");
    rocket::build().mount("/", routes![test])
}

src\bin\main.rs

mod web_page;

fn main() {

    thread::spawn(|| {
         web_page::rocket().launch()
    });

//other code

}

It only write Rocket start. But server does not work in the background. I tried to check by going to 127.0.0.1:8000/test, but nothing happened. But when I launch with cargo run --bin web_page, everything works. I want the code to work in parallel and independently of everything else, but at the same time not stop my main one.


Solution

  • I was able to solve this problem using asynchrony and a new thread. Now, I have a new thread created, after which my main code runs in parallel

    web_pages.rs

    #[get("/<identifier>")]
    fn test(identifier: &str) -> String {
        format!("Your identifier is {}", identifier)
    }
    
    
    #[launch]
    pub fn rocket() -> _ {
    
        println!("Rocket started");
        rocket::build().mount("/", routes![test])
    

    main.rs

    use std::thread;
    use tokio::runtime::Runtime;
    use web_page::rocket;
    
    
    #[rocket::main]
    async fn main() {
    
    // Create new thread
    thread::spawn(|| {
        // Create new Tokio runtime
        let rt = Runtime::new().unwrap();
    
        // Create async function
        rt.block_on(async {
            
            let _start = rocket().launch().await;
        });
    });
    
    // Another code
    }