Rocket: mount sub-application

Rocket

examples/rocket/mount-sub-application/Cargo.toml

[package]
name = "mount-sub-application"
version = "0.1.0"
edition = "2021"

[dependencies]
rocket = "0.5.0"

examples/rocket/mount-sub-application/src/admin.rs

//#[macro_use]
//extern crate rocket;
use rocket::Route;


pub fn routes() -> Vec<Route> {
    routes![main, list]
}

#[get("/")]
fn main() -> &'static str {
    "Admin main page"
}

#[get("/list")]
fn list() -> &'static str {
    "Admin list page"
}

examples/rocket/mount-sub-application/src/main.rs

#[macro_use]
extern crate rocket;

pub(crate) mod admin;

#[get("/")]
fn index() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![index])
    .mount("/admin", admin::routes())
}

#[cfg(test)]
mod tests;

#[cfg(test)]
mod test_admin;

examples/rocket/mount-sub-application/src/test_admin.rs

use rocket::http::Status;
use rocket::local::blocking::Client;

#[test]
fn admin_main() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client.get("/admin").dispatch();

    assert_eq!(response.status(), Status::Ok);
    assert_eq!(response.into_string(), Some("Admin main page".into()));
}

examples/rocket/mount-sub-application/src/tests.rs

use rocket::http::Status;
use rocket::local::blocking::Client;

#[test]
fn hello_world() {
    let client = Client::tracked(super::rocket()).unwrap();
    let response = client.get("/").dispatch();

    assert_eq!(response.status(), Status::Ok);
    assert_eq!(response.into_string(), Some("Hello, world!".into()));
}

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo