nxyt
nxyt

Reputation: 115

Is there a way to split server routes declaration in actix-web?

I have the following server declaration right now

let server = HttpServer::new(move || {
    App::new()
        .app_data(actix_web::web::Data::new(pool.clone()))
        .service(ping)
        .service(stock::controller::get_all)
        .service(stock::controller::find_one)
        .service(stock::controller::insert_one)
        .service(stock::controller::insert_many)
})
.bind(("127.0.0.1", 7777))?
.run();

I feel like it will be very hard to control it when I'll add other routes. Is there a way to split it so I could have something like

App::new()
        .app_data(actix_web::web::Data::new(pool.clone()))
        .service(ping)
        .service(stock::controller::routes)

And have the routes function add all the services declared in first code sample?

Upvotes: 4

Views: 2288

Answers (1)

aedm
aedm

Reputation: 6584

You can create a route scope:

HttpServer::new(|| {
    let stocks_controller = actix_web::web::scope("/stocks")
        .service(get_all)
        .service(find_one)
        .service(insert_one);
    App::new()
        .service(ping)
        .service(stocks_controller)
})

More info here.

Upvotes: 5

Related Questions