Actix web implement App outside of the main

Hi,

Let's take the basic Actix Web example

use actix_web::{web, App, HttpServer, Responder};

async fn index() -> impl Responder {
    "Hello world!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(
            web::scope("/app")
                .route("/index.html", web::get().to(index)),
        )
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

How could I instanciate an App outside of the main function, to get something like :

use actix_web::{web, App, HttpServer, Responder};

async fn index() -> impl Responder {
    "Hello world!"
}

// Function to initialize the App
fn init_app() -> App {
    App::new()
        .service(web::scope("/app").route("/index.html", web::get().to(index)))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(init_app())
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

For now, with this code, I got this :

missing generics for struct `App`
expected 1 generic argument
note: struct defined here, with 1 generic parameter: `T`
  --> /actix-web-4.4.1/src/app.rs:25:12
help: add missing generic argument

I don't really understand what is asked by the compiler. If I add <T> to the type returned by the function init_app, I get the error

cannot find type `T` in this scope

What does the compiler expect for ?

1 Like

I don't recall if naming T was actually impossible or if it requires a terribly complex type, but either way, passing App<T> around isn't really the way to go. What you want to use is App::configure instead:

use actix_web::{web, App, HttpServer, Responder};

async fn index() -> impl Responder {
    "Hello world!"
}

// Function to initialize the App
fn init_app(cfg: &mut web::ServiceConfig) {
    cfg.service(web::scope("/app").route("/index.html", web::get().to(index)))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(App::configure(init_app))
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}
2 Likes

Thanks @jofas, it's working !

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.