I'm just starting to learn Rust Axum and I'm wondering how I should structure my project.
Right now, my project is a simple in memory to-do app stolen from a YouTube tutorial, where he defines a router for the specific folder. Structure right now looks like this:
.
├── Cargo.lock
├── Cargo.toml
└── src
├── in_memory
│ ├── mod.rs
│ ├── routes.rs
│ └── state.rs
└── main.rs
I do not feel comfortable with the functions being used for routes all written in the same file, but I'm ok whit it being like that.
If someone knows if I can write a file where then I could import the functionality awesome.
Now my problem is the following:
If I want to make my project bigger and add another section, where should I put all the new code? Am I obliged to use the same file?
You can definitely split your routes into separate files. You can return Router
s from functions configuring your sub routes and then .merge()
them in your main file.
src/
- routes/
- route1.rs
- route2.rs
- routes.rs
- main.rs
// route1.rs / route2.rs
pub async fn list() -> impl IntoResponse { ... }
pub fn get_routes() -> Router {
Router::new()
.route("/", get(list))
// ... other routes
}
// routes.rs
mod route1;
mod route2;
// main.rs
#[tokio::main]
async fn main() -> Result<(), Error> {
let app = Router::new()
.merge(routes::route1::get_routes())
.merge(routes::route2::get_routes());
run(app).await
}
Read also Separate Modules into different files.