Struct rocket::Rocket[][src]

pub struct Rocket { /* fields omitted */ }

The main Rocket type: used to mount routes and catchers and launch the application.

Implementations

impl Rocket[src]

pub fn ignite() -> Rocket[src]

Create a new Rocket application using the configuration information in Rocket.toml. If the file does not exist or if there is an I/O error reading the file, the defaults, overridden by any environment-based paramparameters, are used. See the config documentation for more information on defaults.

This method is typically called through the rocket::ignite() alias.

Panics

If there is an error reading configuration sources, this function prints a nice error message and then exits the process.

Examples

rocket::ignite()

pub fn custom<T: Provider>(provider: T) -> Rocket[src]

Creates a new Rocket application using the supplied configuration provider. This method is typically called through the rocket::custom() alias.

Panics

If there is an error reading configuration sources, this function prints a nice error message and then exits the process.

Examples

use figment::{Figment, providers::{Toml, Env, Format}};

#[rocket::launch]
fn rocket() -> _ {
    let figment = Figment::from(rocket::Config::default())
        .merge(Toml::file("MyApp.toml").nested())
        .merge(Env::prefixed("MY_APP_"));

    rocket::custom(figment)
}

pub fn mount<R: Into<Vec<Route>>>(self, base: &str, routes: R) -> Self[src]

Mounts all of the routes in the supplied vector at the given base path. Mounting a route with path path at path base makes the route available at base/path.

Panics

Panics if the base mount point is not a valid static path: a valid origin URI without dynamic parameters.

Panics if any route’s URI is not a valid origin URI. This kind of panic is guaranteed not to occur if the routes were generated using Rocket’s code generation.

Examples

Use the routes! macro to mount routes created using the code generation facilities. Requests to the /hello/world URI will be dispatched to the hi route.

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

#[launch]
fn rocket() -> rocket::Rocket {
    rocket::ignite().mount("/hello", routes![hi])
}

Manually create a route named hi at path "/world" mounted at base "/hello". Requests to the /hello/world URI will be dispatched to the hi route.

use rocket::{Request, Route, Data};
use rocket::handler::{HandlerFuture, Outcome};
use rocket::http::Method::*;

fn hi<'r>(req: &'r Request, _: Data) -> HandlerFuture<'r> {
    Outcome::from(req, "Hello!").pin()
}

rocket::ignite().mount("/hello", vec![Route::new(Get, "/world", hi)])

pub fn register(self, catchers: Vec<Catcher>) -> Self[src]

Registers all of the catchers in the supplied vector.

Examples

use rocket::Request;

#[catch(500)]
fn internal_error() -> &'static str {
    "Whoops! Looks like we messed up."
}

#[catch(400)]
fn not_found(req: &Request) -> String {
    format!("I couldn't find '{}'. Try something else?", req.uri())
}

#[launch]
fn rocket() -> rocket::Rocket {
    rocket::ignite().register(catchers![internal_error, not_found])
}

pub fn manage<T: Send + Sync + 'static>(self, state: T) -> Self[src]

Add state to the state managed by this instance of Rocket.

This method can be called any number of times as long as each call refers to a different T.

Managed state can be retrieved by any request handler via the State request guard. In particular, if a value of type T is managed by Rocket, adding State<T> to the list of arguments in a request handler instructs Rocket to retrieve the managed value.

Panics

Panics if state of type T is already being managed.

Example

use rocket::State;

struct MyValue(usize);

#[get("/")]
fn index(state: State<MyValue>) -> String {
    format!("The stateful value is: {}", state.0)
}

#[launch]
fn rocket() -> rocket::Rocket {
    rocket::ignite()
        .mount("/", routes![index])
        .manage(MyValue(10))
}

pub fn attach<F: Fairing>(self, fairing: F) -> Self[src]

Attaches a fairing to this instance of Rocket. If the fairing is an attach fairing, it is run immediately. All other kinds of fairings will be executed at their appropriate time.

Example

use rocket::Rocket;
use rocket::fairing::AdHoc;

#[launch]
fn rocket() -> rocket::Rocket {
    rocket::ignite()
        .attach(AdHoc::on_launch("Launch Message", |_| {
            println!("Rocket is launching!");
        }))
}

pub fn config(&self) -> &Config[src]

Returns the active configuration.

Example

use rocket::Rocket;
use rocket::fairing::AdHoc;

#[launch]
fn rocket() -> rocket::Rocket {
    rocket::ignite()
        .attach(AdHoc::on_launch("Config Printer", |rocket| {
            println!("Rocket launch config: {:?}", rocket.config());
        }))
}

pub fn figment(&self) -> &Figment[src]

Returns the figment for configured provider.

Example

let rocket = rocket::ignite();
let figment = rocket.figment();

let port: u16 = figment.extract_inner("port").unwrap();
assert_eq!(port, rocket.config().port);

pub fn routes(&self) -> impl Iterator<Item = &Route> + '_[src]

Returns an iterator over all of the routes mounted on this instance of Rocket. The order is unspecified.

Example

use rocket::Rocket;
use rocket::fairing::AdHoc;

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

fn main() {
    let mut rocket = rocket::ignite()
        .mount("/", routes![hello])
        .mount("/hi", routes![hello]);

    for route in rocket.routes() {
        match route.base() {
            "/" => assert_eq!(route.uri.path(), "/hello"),
            "/hi" => assert_eq!(route.uri.path(), "/hi/hello"),
            _ => unreachable!("only /hello, /hi/hello are expected")
        }
    }

    assert_eq!(rocket.routes().count(), 2);
}

pub fn catchers(&self) -> impl Iterator<Item = &Catcher> + '_[src]

Returns an iterator over all of the catchers registered on this instance of Rocket. The order is unspecified.

Example

use rocket::Rocket;
use rocket::fairing::AdHoc;

#[catch(404)] fn not_found() -> &'static str { "Nothing here, sorry!" }
#[catch(500)] fn just_500() -> &'static str { "Whoops!?" }
#[catch(default)] fn some_default() -> &'static str { "Everything else." }

fn main() {
    let mut rocket = rocket::ignite()
        .register(catchers![not_found, just_500, some_default]);

    let mut codes: Vec<_> = rocket.catchers().map(|c| c.code).collect();
    codes.sort();

    assert_eq!(codes, vec![None, Some(404), Some(500)]);
}

pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T>[src]

Returns Some of the managed state value for the type T if it is being managed by self. Otherwise, returns None.

Example

#[derive(PartialEq, Debug)]
struct MyState(&'static str);

let rocket = rocket::ignite().manage(MyState("hello!"));
assert_eq!(rocket.state::<MyState>(), Some(&MyState("hello!")));

pub fn shutdown(&self) -> Shutdown[src]

Returns a handle which can be used to gracefully terminate this instance of Rocket. In routes, use the Shutdown request guard.

Example

let mut rocket = rocket::ignite();
let handle = rocket.shutdown();

thread::spawn(move || {
    thread::sleep(Duration::from_secs(10));
    handle.shutdown();
});

// Shuts down after 10 seconds
let shutdown_result = rocket.launch().await;
assert!(shutdown_result.is_ok());

pub async fn launch(self) -> Result<(), Error>[src]

Returns a Future that drives the server, listening for and dispatching requests to mounted routes and catchers. The Future completes when the server is shut down via Shutdown, encounters a fatal error, or if the the ctrlc configuration option is set, when Ctrl+C is pressed.

Error

If there is a problem starting the application, an Error is returned. Note that a value of type Error panics if dropped without first being inspected. See the Error documentation for more information.

Example

#[rocket::main]
async fn main() {
    let result = rocket::ignite().launch().await;
    assert!(result.is_ok());
}

Auto Trait Implementations

impl !RefUnwindSafe for Rocket

impl Send for Rocket

impl Sync for Rocket

impl Unpin for Rocket

impl !UnwindSafe for Rocket

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T> Instrument for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> IntoCollection<T> for T

impl<T> Same<T> for T

type Output = T

Should always be Self

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<V, T> VZip<V> for T where
    V: MultiLane<T>,