Search code examples
rustactix-web

How to register routes in a different function with actix-web?


I'm creating an actix-web application and I would like to register routes in a separate function. However, I cannot write a function that takes and returns App::new() since AppEntry is private:

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

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        let app = App::new();
        register_routes(&app)
    })
        .bind(("127.0.0.1", 8080))?
        .run()
        .await
}

fn register_routes(app: App<AppEntry>) -> App<AppEntry> {
    App::new()
        .route("/hey", web::get().to(hello))
}

async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hey there!")
}
error[E0412]: cannot find type `AppEntry` in this scope
  --> src/main.rs:14:29
   |
14 | fn register_routes(app: App<AppEntry>) -> App<AppEntry> {
   |                   -         ^^^^^^^^ not found in this scope
   |                   |
   |                   help: you might be missing a type parameter: `<AppEntry>`

How should I write the register_routes function?


Solution

  • You can use App::configure for that, avoiding the need to pass an App<AppEntry> directly, like they show in this example.

    By the way, in your register_routes function, you just create another, new App, you don't actually use the one that you pass in.