Add '#[rocket::main]' attribute and make 'launch()' an 'async fn'.

'#[rocket::main]' works like '#[rocket::async_test]', but it uses
tokio's multithreaded scheduler.
This commit is contained in:
Jeb Rosen 2020-06-14 08:57:55 -07:00 committed by Sergio Benitez
parent 7a62653cdd
commit bc1b90cbdb
48 changed files with 292 additions and 203 deletions

View File

@ -62,10 +62,12 @@
//! #[database("sqlite_logs")] //! #[database("sqlite_logs")]
//! struct LogsDbConn(diesel::SqliteConnection); //! struct LogsDbConn(diesel::SqliteConnection);
//! //!
//! fn main() { //! #[rocket::main]
//! async fn main() {
//! rocket::ignite() //! rocket::ignite()
//! .attach(LogsDbConn::fairing()) //! .attach(LogsDbConn::fairing())
//! .launch(); //! .launch()
//! .await;
//! } //! }
//! # } fn main() {} //! # } fn main() {}
//! ``` //! ```
@ -150,7 +152,8 @@
//! use std::collections::HashMap; //! use std::collections::HashMap;
//! use rocket::config::{Config, Environment, Value}; //! use rocket::config::{Config, Environment, Value};
//! //!
//! fn main() { //! #[rocket::main]
//! async fn main() {
//! let mut database_config = HashMap::new(); //! let mut database_config = HashMap::new();
//! let mut databases = HashMap::new(); //! let mut databases = HashMap::new();
//! //!
@ -164,7 +167,7 @@
//! .finalize() //! .finalize()
//! .unwrap(); //! .unwrap();
//! //!
//! rocket::custom(config).launch(); //! rocket::custom(config).launch().await;
//! } //! }
//! # } fn main() {} //! # } fn main() {}
//! ``` //! ```
@ -263,7 +266,8 @@
//! #[database("my_db")] //! #[database("my_db")]
//! struct MyDatabase(diesel::SqliteConnection); //! struct MyDatabase(diesel::SqliteConnection);
//! //!
//! fn main() { //! #[rocket::main]
//! async fn main() {
//! # let mut db_config = HashMap::new(); //! # let mut db_config = HashMap::new();
//! # let mut databases = HashMap::new(); //! # let mut databases = HashMap::new();
//! # //! #
@ -278,7 +282,8 @@
//! # //! #
//! rocket::custom(config) //! rocket::custom(config)
//! .attach(MyDatabase::fairing()) //! .attach(MyDatabase::fairing())
//! .launch(); //! .launch()
//! .await;
//! } //! }
//! # } fn main() {} //! # } fn main() {}
//! ``` //! ```

View File

@ -135,11 +135,13 @@ impl std::ops::BitOr for Options {
/// # extern crate rocket_contrib; /// # extern crate rocket_contrib;
/// use rocket_contrib::serve::StaticFiles; /// use rocket_contrib::serve::StaticFiles;
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { /// # if false {
/// rocket::ignite() /// rocket::ignite()
/// .mount("/public", StaticFiles::from("/static")) /// .mount("/public", StaticFiles::from("/static"))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -161,11 +163,13 @@ impl std::ops::BitOr for Options {
/// # extern crate rocket_contrib; /// # extern crate rocket_contrib;
/// use rocket_contrib::serve::StaticFiles; /// use rocket_contrib::serve::StaticFiles;
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { /// # if false {
/// rocket::ignite() /// rocket::ignite()
/// .mount("/", StaticFiles::from(concat!(env!("CARGO_MANIFEST_DIR"), "/static"))) /// .mount("/", StaticFiles::from(concat!(env!("CARGO_MANIFEST_DIR"), "/static")))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -196,11 +200,13 @@ impl StaticFiles {
/// # extern crate rocket_contrib; /// # extern crate rocket_contrib;
/// use rocket_contrib::serve::StaticFiles; /// use rocket_contrib::serve::StaticFiles;
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { /// # if false {
/// rocket::ignite() /// rocket::ignite()
/// .mount("/static", StaticFiles::from("/www/public")) /// .mount("/static", StaticFiles::from("/www/public"))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -212,11 +218,13 @@ impl StaticFiles {
/// # extern crate rocket_contrib; /// # extern crate rocket_contrib;
/// use rocket_contrib::serve::StaticFiles; /// use rocket_contrib::serve::StaticFiles;
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { /// # if false {
/// rocket::ignite() /// rocket::ignite()
/// .mount("/static", StaticFiles::from("/www/public").rank(30)) /// .mount("/static", StaticFiles::from("/www/public").rank(30))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -240,13 +248,15 @@ impl StaticFiles {
/// # extern crate rocket_contrib; /// # extern crate rocket_contrib;
/// use rocket_contrib::serve::{StaticFiles, Options}; /// use rocket_contrib::serve::{StaticFiles, Options};
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { /// # if false {
/// let options = Options::Index | Options::DotFiles; /// let options = Options::Index | Options::DotFiles;
/// rocket::ignite() /// rocket::ignite()
/// .mount("/static", StaticFiles::from("/www/public")) /// .mount("/static", StaticFiles::from("/www/public"))
/// .mount("/pub", StaticFiles::new("/www/public", options).rank(-1)) /// .mount("/pub", StaticFiles::new("/www/public", options).rank(-1))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```

View File

@ -0,0 +1,83 @@
use proc_macro::{TokenStream, Span};
use devise::{syn, Result};
use crate::proc_macro2::TokenStream as TokenStream2;
use crate::syn_ext::syn_to_diag;
#[derive(Copy, Clone)]
enum Kind {
Main,
Test,
}
impl Kind {
// The name of the attribute, used for error messages
fn attr_name(&self) -> &'static str {
match self {
Kind::Main => "main",
Kind::Test => "async_test",
}
}
// Attributes to decorate the generated function with
fn attrs(&self) -> Option<TokenStream2> {
match self {
Kind::Main => None,
Kind::Test => Some(quote!{ #[test] }),
}
}
// The path to the function to call
fn fn_path(&self) -> TokenStream2 {
match self {
Kind::Main => quote! { rocket :: async_main },
Kind::Test => quote! { rocket :: async_test },
}
}
}
fn parse_input(input: TokenStream, attr_name: &str) -> Result<syn::ItemFn> {
let function: syn::ItemFn = syn::parse(input).map_err(syn_to_diag)
.map_err(|diag| diag.help(format!("`#[{}]` can only be applied to async functions", attr_name)))?;
if function.sig.asyncness.is_none() {
return Err(Span::call_site().error(format!("`#[{}]` can only be applied to async functions", attr_name)))
}
if !function.sig.inputs.is_empty() {
return Err(Span::call_site().error(format!("`#[{}]` can only be applied to functions with no parameters", attr_name)));
}
Ok(function)
}
fn _async_entry(_args: TokenStream, input: TokenStream, kind: Kind) -> Result<TokenStream> {
let function = parse_input(input, kind.attr_name())?;
let attrs = &function.attrs;
let vis = &function.vis;
let name = &function.sig.ident;
let output = &function.sig.output;
let body = &function.block;
let test_attr = kind.attrs();
let fn_path = kind.fn_path();
Ok(quote! {
#test_attr
#(#attrs)*
#vis fn #name() #output {
#fn_path (async move {
#body
})
}
}.into())
}
pub fn async_test_attribute(args: TokenStream, input: TokenStream) -> TokenStream {
_async_entry(args, input, Kind::Test).unwrap_or_else(|d| { d.emit(); TokenStream::new() })
}
pub fn main_attribute(args: TokenStream, input: TokenStream) -> TokenStream {
_async_entry(args, input, Kind::Main).unwrap_or_else(|d| { d.emit(); TokenStream::new() })
}

View File

@ -1,43 +0,0 @@
use proc_macro::{TokenStream, Span};
use devise::{syn, Result};
use crate::syn_ext::syn_to_diag;
fn parse_input(input: TokenStream) -> Result<syn::ItemFn> {
let function: syn::ItemFn = syn::parse(input).map_err(syn_to_diag)
.map_err(|diag| diag.help("`#[async_test]` can only be applied to async functions"))?;
if function.sig.asyncness.is_none() {
return Err(Span::call_site().error("`#[async_test]` can only be applied to async functions"))
}
if !function.sig.inputs.is_empty() {
return Err(Span::call_site().error("`#[async_test]` can only be applied to functions with no parameters"));
}
Ok(function)
}
pub fn _async_test(_args: TokenStream, input: TokenStream) -> Result<TokenStream> {
let function = parse_input(input)?;
let attrs = &function.attrs;
let vis = &function.vis;
let name = &function.sig.ident;
let output = &function.sig.output;
let body = &function.block;
Ok(quote! {
#[test]
#(#attrs)*
#vis fn #name() #output {
rocket::async_test(async move {
#body
})
}
}.into())
}
pub fn async_test_attribute(args: TokenStream, input: TokenStream) -> TokenStream {
_async_test(args, input).unwrap_or_else(|d| { d.emit(); TokenStream::new() })
}

View File

@ -1,4 +1,4 @@
pub mod async_test; pub mod async_entry;
pub mod catch; pub mod catch;
pub mod route; pub mod route;
pub mod segments; pub mod segments;

View File

@ -407,7 +407,12 @@ pub fn catch(args: TokenStream, input: TokenStream) -> TokenStream {
#[proc_macro_attribute] #[proc_macro_attribute]
pub fn async_test(args: TokenStream, input: TokenStream) -> TokenStream { pub fn async_test(args: TokenStream, input: TokenStream) -> TokenStream {
emit!(attribute::async_test::async_test_attribute(args, input)) emit!(attribute::async_entry::async_test_attribute(args, input))
}
#[proc_macro_attribute]
pub fn main(args: TokenStream, input: TokenStream) -> TokenStream {
emit!(attribute::async_entry::main_attribute(args, input))
} }
/// Derive for the [`FromFormValue`] trait. /// Derive for the [`FromFormValue`] trait.

View File

@ -52,9 +52,10 @@ use yansi::Color::*;
/// format!("I couldn't find '{}'. Try something else?", req.uri()) /// format!("I couldn't find '{}'. Try something else?", req.uri())
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { // We don't actually want to launch the server in an example. /// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite().register(catchers![internal_error, not_found]).launch(); /// rocket::ignite().register(catchers![internal_error, not_found]).launch().await;
/// # } /// # }
/// } /// }
/// ``` /// ```

View File

@ -65,8 +65,8 @@ pub enum LaunchErrorKind {
/// ```rust /// ```rust
/// use rocket::error::Error; /// use rocket::error::Error;
/// ///
/// # if false { /// # let _ = async {
/// if let Err(error) = rocket::ignite().launch() { /// if let Err(error) = rocket::ignite().launch().await {
/// match error { /// match error {
/// Error::Launch(error) => { /// Error::Launch(error) => {
/// // This case is only reached if launching failed. This println "inspects" the error. /// // This case is only reached if launching failed. This println "inspects" the error.
@ -82,20 +82,20 @@ pub enum LaunchErrorKind {
/// } /// }
/// } /// }
/// ///
/// # } /// # };
/// ``` /// ```
/// ///
/// When a value of this type panics, the corresponding error message is pretty /// When a value of this type panics, the corresponding error message is pretty
/// printed to the console. The following illustrates this: /// printed to the console. The following illustrates this:
/// ///
/// ```rust /// ```rust
/// # if false { /// # let _ = async {
/// let error = rocket::ignite().launch(); /// let error = rocket::ignite().launch().await;
/// ///
/// // This call to drop (explicit here for demonstration) will result in /// // This call to drop (explicit here for demonstration) will result in
/// // `error` being pretty-printed to the console along with a `panic!`. /// // `error` being pretty-printed to the console along with a `panic!`.
/// drop(error); /// drop(error);
/// # } /// # };
/// ``` /// ```
/// ///
/// # Usage /// # Usage
@ -136,14 +136,14 @@ impl LaunchError {
/// ///
/// ```rust /// ```rust
/// use rocket::error::Error; /// use rocket::error::Error;
/// # if false { /// # let _ = async {
/// if let Err(error) = rocket::ignite().launch() { /// if let Err(error) = rocket::ignite().launch().await {
/// match error { /// match error {
/// Error::Launch(err) => println!("Found a launch error: {}", err.kind()), /// Error::Launch(err) => println!("Found a launch error: {}", err.kind()),
/// Error::Run(err) => println!("Error at runtime"), /// Error::Run(err) => println!("Error at runtime"),
/// } /// }
/// } /// }
/// # } /// # };
/// ``` /// ```
#[inline] #[inline]
pub fn kind(&self) -> &LaunchErrorKind { pub fn kind(&self) -> &LaunchErrorKind {

View File

@ -65,11 +65,13 @@ pub type HandlerFuture<'r> = BoxFuture<'r, Outcome<'r>>;
/// } /// }
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { /// # if false {
/// rocket::ignite() /// rocket::ignite()
/// .mount("/", CustomHandler(Kind::Simple)) /// .mount("/", CustomHandler(Kind::Simple))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -112,12 +114,14 @@ pub type HandlerFuture<'r> = BoxFuture<'r, Outcome<'r>>;
/// } /// }
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { /// # if false {
/// rocket::ignite() /// rocket::ignite()
/// .mount("/", routes![custom_handler]) /// .mount("/", routes![custom_handler])
/// .manage(Kind::Simple) /// .manage(Kind::Simple)
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```

View File

@ -67,9 +67,10 @@
//! "Hello, world!" //! "Hello, world!"
//! } //! }
//! //!
//! fn main() { //! #[rocket::main]
//! async fn main() {
//! # if false { // We don't actually want to launch the server in an example. //! # if false { // We don't actually want to launch the server in an example.
//! rocket::ignite().mount("/", routes![hello]).launch(); //! rocket::ignite().mount("/", routes![hello]).launch().await;
//! # } //! # }
//! } //! }
//! ``` //! ```
@ -164,3 +165,14 @@ pub fn async_test<R>(fut: impl std::future::Future<Output = R> + Send) -> R {
.expect("create tokio runtime") .expect("create tokio runtime")
.block_on(fut) .block_on(fut)
} }
/// WARNING: This is unstable! Do not use this method outside of Rocket!
#[doc(hidden)]
pub fn async_main<R>(fut: impl std::future::Future<Output = R> + Send) -> R {
tokio::runtime::Builder::new()
.threaded_scheduler()
.enable_all()
.build()
.expect("create tokio runtime")
.block_on(fut)
}

View File

@ -42,7 +42,8 @@ use crate::http::Status;
/// state.inner().user_val.as_str() /// state.inner().user_val.as_str()
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// let config = MyConfig { /// let config = MyConfig {
/// user_val: "user input".to_string() /// user_val: "user input".to_string()
/// }; /// };
@ -51,7 +52,8 @@ use crate::http::Status;
/// rocket::ignite() /// rocket::ignite()
/// .mount("/", routes![index, raw_config_value]) /// .mount("/", routes![index, raw_config_value])
/// .manage(config) /// .manage(config)
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```

View File

@ -69,9 +69,10 @@ const FLASH_COOKIE_DELIM: char = ':';
/// .unwrap_or_else(|| "Welcome!".to_string()) /// .unwrap_or_else(|| "Welcome!".to_string())
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { // We don't actually want to launch the server in an example. /// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite().mount("/", routes![login, index]).launch(); /// rocket::ignite().mount("/", routes![login, index]).launch().await;
/// # } /// # }
/// } /// }
/// ``` /// ```

View File

@ -656,10 +656,11 @@ impl Rocket {
/// "Hello!" /// "Hello!"
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { // We don't actually want to launch the server in an example. /// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite().mount("/hello", routes![hi]) /// rocket::ignite().mount("/hello", routes![hi])
/// # .launch(); /// # .launch().await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -677,10 +678,10 @@ impl Rocket {
/// Outcome::from(req, "Hello!") /// Outcome::from(req, "Hello!")
/// } /// }
/// ///
/// # if false { // We don't actually want to launch the server in an example. /// # let _ = async { // We don't actually want to launch the server in an example.
/// rocket::ignite().mount("/hello", vec![Route::new(Get, "/world", hi)]) /// rocket::ignite().mount("/hello", vec![Route::new(Get, "/world", hi)])
/// # .launch(); /// # .launch().await;
/// # } /// # };
/// ``` /// ```
#[inline] #[inline]
pub fn mount<R: Into<Vec<Route>>>(mut self, base: &str, routes: R) -> Self { pub fn mount<R: Into<Vec<Route>>>(mut self, base: &str, routes: R) -> Self {
@ -718,11 +719,12 @@ impl Rocket {
/// format!("I couldn't find '{}'. Try something else?", req.uri()) /// format!("I couldn't find '{}'. Try something else?", req.uri())
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { // We don't actually want to launch the server in an example. /// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite() /// rocket::ignite()
/// .register(catchers![internal_error, not_found]) /// .register(catchers![internal_error, not_found])
/// # .launch(); /// # .launch().await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -760,12 +762,14 @@ impl Rocket {
/// format!("The stateful value is: {}", state.0) /// format!("The stateful value is: {}", state.0)
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { // We don't actually want to launch the server in an example. /// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite() /// rocket::ignite()
/// .mount("/", routes![index]) /// .mount("/", routes![index])
/// .manage(MyValue(10)) /// .manage(MyValue(10))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -795,13 +799,15 @@ impl Rocket {
/// use rocket::Rocket; /// use rocket::Rocket;
/// use rocket::fairing::AdHoc; /// use rocket::fairing::AdHoc;
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { // We don't actually want to launch the server in an example. /// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite() /// rocket::ignite()
/// .attach(AdHoc::on_launch("Launch Message", |_| { /// .attach(AdHoc::on_launch("Launch Message", |_| {
/// println!("Rocket is launching!"); /// println!("Rocket is launching!");
/// })) /// }))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```
@ -863,15 +869,15 @@ impl Rocket {
/// # Example /// # Example
/// ///
/// ```rust /// ```rust
/// #[tokio::main] /// #[rocket::main]
/// async fn main() { /// async fn main() {
/// # if false { /// # if false {
/// let result = rocket::ignite().launch(); /// let result = rocket::ignite().launch().await;
/// assert!(result.is_ok()); /// assert!(result.is_ok());
/// # } /// # }
/// } /// }
/// ``` /// ```
async fn serve(self) -> Result<(), crate::error::Error> { pub async fn launch(self) -> Result<(), crate::error::Error> {
use std::net::ToSocketAddrs; use std::net::ToSocketAddrs;
use crate::error::Error::Launch; use crate::error::Error::Launch;
@ -954,40 +960,6 @@ impl Rocket {
server.await server.await
} }
/// Starts the application server and begins listening for and dispatching
/// requests to mounted routes and catchers. This function does not return
/// unless a shutdown is requested via a [`ShutdownHandle`] or there is an
/// error.
///
/// This is a convenience function that creates a suitable default runtime
/// and launches the server on that runtime. If you already have a runtime,
/// use the [`Rocket::serve`] method instead.
///
/// # Error
///
/// If there is a problem starting the application, a [`LaunchError`] is
/// returned. Note that a value of type `LaunchError` panics if dropped
/// without first being inspected. See the [`LaunchError`] documentation for
/// more information.
///
/// # Example
///
/// ```rust
/// # if false {
/// rocket::ignite().launch();
/// # }
/// ```
pub fn launch(self) -> Result<(), crate::error::Error> {
// Initialize the tokio runtime
let mut runtime = tokio::runtime::Builder::new()
.threaded_scheduler()
.enable_all()
.build()
.expect("Cannot build runtime!");
runtime.block_on(async move { self.serve().await })
}
pub(crate) fn _manifest(&self) -> &Manifest { pub(crate) fn _manifest(&self) -> &Manifest {
self.manifest.as_ref().expect("internal error: manifest was taken and not replaced. \ self.manifest.as_ref().expect("internal error: manifest was taken and not replaced. \
Was `inspect()` called but not polled to completion?") Was `inspect()` called but not polled to completion?")
@ -1079,7 +1051,7 @@ impl Manifest {
/// }); /// });
/// ///
/// // Shuts down after 10 seconds /// // Shuts down after 10 seconds
/// let shutdown_result = rocket.launch(); /// let shutdown_result = rocket.launch().await;
/// assert!(shutdown_result.is_ok()); /// assert!(shutdown_result.is_ok());
/// # } /// # }
/// # }); /// # });
@ -1160,13 +1132,15 @@ impl Manifest {
/// use rocket::Rocket; /// use rocket::Rocket;
/// use rocket::fairing::AdHoc; /// use rocket::fairing::AdHoc;
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { // We don't actually want to launch the server in an example. /// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite() /// rocket::ignite()
/// .attach(AdHoc::on_launch("Config Printer", |manifest| { /// .attach(AdHoc::on_launch("Config Printer", |manifest| {
/// println!("Rocket launch config: {:?}", manifest.config()); /// println!("Rocket launch config: {:?}", manifest.config());
/// })) /// }))
/// .launch(); /// .launch()
/// .await;
/// # } /// # }
/// } /// }
/// ``` /// ```

View File

@ -24,11 +24,13 @@ use tokio::sync::mpsc;
/// "Shutting down..." /// "Shutting down..."
/// } /// }
/// ///
/// fn main() { /// #[rocket::main]
/// async fn main() {
/// # if false { /// # if false {
/// rocket::ignite() /// rocket::ignite()
/// .mount("/", routes![shutdown]) /// .mount("/", routes![shutdown])
/// .launch() /// .launch()
/// .await
/// .expect("server failed unexpectedly"); /// .expect("server failed unexpectedly");
/// # } /// # }
/// } /// }

View File

@ -1,4 +1,5 @@
// This example's illustration is the Rocket.toml file. // This example's illustration is the Rocket.toml file.
fn main() { #[rocket::main]
let _ = rocket::ignite().launch(); async fn main() {
let _ = rocket::ignite().launch().await;
} }

View File

@ -63,9 +63,10 @@ fn not_found(request: &Request<'_>) -> Html<String> {
Html(html) Html(html)
} }
fn main() { #[rocket::main]
async fn main() {
let _ = rocket::ignite() let _ = rocket::ignite()
.mount("/hello", routes![get_hello, post_hello]) .mount("/hello", routes![get_hello, post_hello])
.register(catchers![not_found]) .register(catchers![not_found])
.launch(); .launch().await;
} }

View File

@ -38,6 +38,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![submit, index]).attach(Template::fairing()) rocket::ignite().mount("/", routes![submit, index]).attach(Template::fairing())
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -18,12 +18,13 @@ fn not_found(req: &rocket::Request<'_>) -> content::Html<String> {
req.uri())) req.uri()))
} }
fn main() { #[rocket::main]
async fn main() {
let result = rocket::ignite() let result = rocket::ignite()
// .mount("/", routes![hello, hello]) // uncoment this to get an error // .mount("/", routes![hello, hello]) // uncoment this to get an error
.mount("/", routes![hello]) .mount("/", routes![hello])
.register(catchers![not_found]) .register(catchers![not_found])
.launch(); .launch().await;
if let Err(e) = result { if let Err(e) = result {
println!("Whoops! Rocket didn't launch!"); println!("Whoops! Rocket didn't launch!");

View File

@ -94,6 +94,7 @@ fn rocket() -> rocket::Rocket {
})) }))
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -45,6 +45,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![index, sink]) rocket::ignite().mount("/", routes![index, sink])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -81,6 +81,7 @@ fn rocket() -> rocket::Rocket {
.mount("/", routes![files::index, files::files, user_page, login]) .mount("/", routes![files::index, files::files, user_page, login])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -77,6 +77,7 @@ fn rocket() -> rocket::Rocket {
})) }))
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -9,6 +9,7 @@ fn hello() -> &'static str {
"Hello, Rust 2018!" "Hello, Rust 2018!"
} }
fn main() { #[rocket::main]
let _ = rocket::ignite().mount("/", routes![hello]).launch(); async fn main() {
let _ = rocket::ignite().mount("/", routes![hello]).launch().await;
} }

View File

@ -14,6 +14,7 @@ fn hi(name: String) -> String {
name name
} }
fn main() { #[rocket::main]
let _ = rocket::ignite().mount("/", routes![hello, hi]).launch(); async fn main() {
let _ = rocket::ignite().mount("/", routes![hello, hi]).launch().await;
} }

View File

@ -9,6 +9,7 @@ fn hello() -> &'static str {
"Hello, world!" "Hello, world!"
} }
fn main() { #[rocket::main]
let _ = rocket::ignite().mount("/", routes![hello]).launch(); async fn main() {
let _ = rocket::ignite().mount("/", routes![hello]).launch().await;
} }

View File

@ -76,6 +76,7 @@ fn rocket() -> rocket::Rocket {
.manage(Mutex::new(HashMap::<ID, String>::new())) .manage(Mutex::new(HashMap::<ID, String>::new()))
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -25,6 +25,7 @@ fn rocket() -> rocket::Rocket {
.manage(LogChannel(SegQueue::new())) .manage(LogChannel(SegQueue::new()))
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -118,6 +118,7 @@ fn rocket() -> rocket::Rocket {
.register(vec![not_found_catcher]) .register(vec![not_found_catcher])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -27,6 +27,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/message", routes![get, create]) rocket::ignite().mount("/message", routes![get, create])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -26,6 +26,7 @@ fn login() -> &'static str {
"Hi! That user doesn't exist. Maybe you need to log in?" "Hi! That user doesn't exist. Maybe you need to log in?"
} }
fn main() { #[rocket::main]
let _ = rocket::ignite().mount("/", routes![root, user, login]).launch(); async fn main() {
let _ = rocket::ignite().mount("/", routes![root, user, login]).launch().await;
} }

View File

@ -55,6 +55,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![index, upload, retrieve]) rocket::ignite().mount("/", routes![index, upload, retrieve])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -36,6 +36,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![hello, hello_20]) rocket::ignite().mount("/", routes![hello, hello_20])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -16,6 +16,7 @@ fn hi(name: String, age: &RawStr) -> String {
format!("Hi {}! Your age ({}) is kind of funky.", name, age) format!("Hi {}! Your age ({}) is kind of funky.", name, age)
} }
fn main() { #[rocket::main]
let _ = rocket::ignite().mount("/", routes![hi, hello]).launch(); async fn main() {
let _ = rocket::ignite().mount("/", routes![hi, hello]).launch().await;
} }

View File

@ -48,6 +48,7 @@ fn rocket() -> Rocket {
.mount("/", routes![hello]) .mount("/", routes![hello])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -21,6 +21,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![index, upload]) rocket::ignite().mount("/", routes![index, upload])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -16,6 +16,7 @@ fn login() -> &'static str {
"Hi! Please log in before continuing." "Hi! Please log in before continuing."
} }
fn main() { #[rocket::main]
let _ = rocket::ignite().mount("/", routes![root, login]).launch(); async fn main() {
let _ = rocket::ignite().mount("/", routes![root, login]).launch().await;
} }

View File

@ -26,8 +26,9 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![header_count]) rocket::ignite().mount("/", routes![header_count])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }
#[cfg(test)] #[cfg(test)]

View File

@ -84,6 +84,7 @@ fn rocket() -> rocket::Rocket {
.mount("/", routes![r_sync, r_async]) .mount("/", routes![r_sync, r_async])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -86,6 +86,7 @@ fn rocket() -> rocket::Rocket {
.mount("/", routes![index, user_index, login, logout, login_user, login_page]) .mount("/", routes![index, user_index, login, logout, login_user, login_page])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -30,6 +30,7 @@ fn rocket() -> rocket::Rocket {
.manage(HitCount(AtomicUsize::new(0))) .manage(HitCount(AtomicUsize::new(0)))
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -9,6 +9,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", StaticFiles::from("static")) rocket::ignite().mount("/", StaticFiles::from("static"))
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -26,6 +26,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![root, file]) rocket::ignite().mount("/", routes![root, file])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -42,6 +42,7 @@ fn rocket() -> rocket::Rocket {
.register(catchers![not_found]) .register(catchers![not_found])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -11,8 +11,9 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![hello]) rocket::ignite().mount("/", routes![hello])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }
#[cfg(test)] #[cfg(test)]

View File

@ -9,6 +9,7 @@ fn hello() -> &'static str {
"Hello, world!" "Hello, world!"
} }
fn main() { #[rocket::main]
let _ = rocket::ignite().mount("/", routes![hello]).launch(); async fn main() {
let _ = rocket::ignite().mount("/", routes![hello]).launch().await;
} }

View File

@ -114,6 +114,7 @@ fn rocket() -> Rocket {
.attach(Template::fairing()) .attach(Template::fairing())
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -37,6 +37,7 @@ fn rocket() -> rocket::Rocket {
rocket::ignite().mount("/", routes![people]) rocket::ignite().mount("/", routes![people])
} }
fn main() { #[rocket::main]
let _ = rocket().launch(); async fn main() {
let _ = rocket().launch().await;
} }

View File

@ -238,9 +238,9 @@ You can find async-ready libraries on [crates.io](https://crates.io) with the
! note ! note
Rocket 0.5 uses the tokio (0.2) runtime. `Rocket::launch()` will automatically Rocket 0.5 uses the tokio (0.2) runtime. The runtime is started for you
start a runtime for you, or you can create a runtime yourself and use if you use `#[rocket::main]`, but you can still `launch()` a rocket
`Rocket::spawn()`. instance on a custom-built `Runtime`.
### Cooperative Multitasking ### Cooperative Multitasking