rustrust-axum

How can I define Axum routes in sub modules?


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. 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?


Solution

  • You can definitely split your routes into separate files. You can return Routers 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.