2016-04-06 20:50:02 +00:00
|
|
|
use std::collections::HashMap;
|
2016-09-25 09:26:15 +00:00
|
|
|
use std::str::from_utf8_unchecked;
|
|
|
|
use std::cmp::min;
|
2016-12-15 08:47:31 +00:00
|
|
|
use std::io::{self, Write};
|
2016-08-24 08:30:09 +00:00
|
|
|
|
2016-04-01 23:54:53 +00:00
|
|
|
use term_painter::Color::*;
|
|
|
|
use term_painter::ToStyle;
|
|
|
|
|
2016-12-16 13:17:16 +00:00
|
|
|
use {logger, handler};
|
2016-12-15 08:47:31 +00:00
|
|
|
use ext::ReadExt;
|
2016-11-04 13:35:04 +00:00
|
|
|
use config::{self, Config};
|
2016-10-25 11:24:07 +00:00
|
|
|
use request::{Request, FormItems};
|
|
|
|
use data::Data;
|
2016-12-15 08:47:31 +00:00
|
|
|
use response::{Body, Response};
|
2016-10-04 00:09:13 +00:00
|
|
|
use router::{Router, Route};
|
|
|
|
use catcher::{self, Catcher};
|
2016-10-08 02:27:26 +00:00
|
|
|
use outcome::Outcome;
|
2016-10-04 00:09:13 +00:00
|
|
|
use error::Error;
|
|
|
|
|
2016-12-15 08:47:31 +00:00
|
|
|
use http::{Method, Status};
|
2016-12-15 17:24:29 +00:00
|
|
|
use http::hyper::{self, header};
|
2016-12-16 11:07:23 +00:00
|
|
|
use http::uri::URI;
|
2016-04-01 23:54:53 +00:00
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
/// The main `Rocket` type: used to mount routes and catchers and launch the
|
2016-10-21 09:56:57 +00:00
|
|
|
/// application.
|
2016-04-01 23:54:53 +00:00
|
|
|
pub struct Rocket {
|
2016-09-08 07:25:40 +00:00
|
|
|
address: String,
|
2016-10-03 10:39:56 +00:00
|
|
|
port: usize,
|
2016-04-06 10:26:43 +00:00
|
|
|
router: Router,
|
2016-10-08 06:20:49 +00:00
|
|
|
default_catchers: HashMap<u16, Catcher>,
|
2016-04-06 20:50:02 +00:00
|
|
|
catchers: HashMap<u16, Catcher>,
|
2016-04-11 10:57:23 +00:00
|
|
|
}
|
|
|
|
|
2016-10-08 11:42:22 +00:00
|
|
|
#[doc(hidden)]
|
2016-12-15 17:24:29 +00:00
|
|
|
impl hyper::Handler for Rocket {
|
2016-11-04 13:35:04 +00:00
|
|
|
// This function tries to hide all of the Hyper-ness from Rocket. It
|
|
|
|
// essentially converts Hyper types into Rocket types, then calls the
|
|
|
|
// `dispatch` function, which knows nothing about Hyper. Because responding
|
|
|
|
// depends on the `HyperResponse` type, this function does the actual
|
|
|
|
// response processing.
|
2016-09-30 22:20:11 +00:00
|
|
|
fn handle<'h, 'k>(&self,
|
2016-12-15 17:24:29 +00:00
|
|
|
hyp_req: hyper::Request<'h, 'k>,
|
|
|
|
res: hyper::FreshResponse<'h>) {
|
2016-10-09 04:37:28 +00:00
|
|
|
// Get all of the information from Hyper.
|
2016-10-09 11:29:02 +00:00
|
|
|
let (_, h_method, h_headers, h_uri, _, h_body) = hyp_req.deconstruct();
|
2016-10-09 04:37:28 +00:00
|
|
|
|
2016-12-16 11:07:23 +00:00
|
|
|
// Convert the Hyper request into a Rocket request.
|
|
|
|
let mut request = match Request::from_hyp(h_method, h_headers, h_uri) {
|
|
|
|
Ok(request) => request,
|
|
|
|
Err(e) => {
|
|
|
|
error!("Bad incoming request: {}", e);
|
|
|
|
let dummy = Request::new(Method::Get, URI::new("<unknown>"));
|
|
|
|
let r = self.handle_error(Status::InternalServerError, &dummy);
|
2016-12-15 08:47:31 +00:00
|
|
|
return self.issue_response(r, res);
|
2016-08-27 01:37:28 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-10-16 07:03:08 +00:00
|
|
|
// Retrieve the data from the hyper body.
|
|
|
|
let data = match Data::from_hyp(h_body) {
|
2016-10-09 11:29:02 +00:00
|
|
|
Ok(data) => data,
|
|
|
|
Err(reason) => {
|
2016-10-16 07:03:08 +00:00
|
|
|
error_!("Bad data in request: {}", reason);
|
2016-12-15 08:47:31 +00:00
|
|
|
let r = self.handle_error(Status::InternalServerError, &request);
|
|
|
|
return self.issue_response(r, res);
|
2016-10-09 11:29:02 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-12-16 13:17:16 +00:00
|
|
|
// Dispatch the request to get a response, then write that response out.
|
|
|
|
let response = self.dispatch(&mut request, data);
|
2016-12-17 17:18:30 +00:00
|
|
|
self.issue_response(response, res)
|
2016-10-16 07:03:08 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Rocket {
|
2016-12-15 08:47:31 +00:00
|
|
|
#[inline]
|
2016-12-15 17:24:29 +00:00
|
|
|
fn issue_response(&self, mut response: Response, hyp_res: hyper::FreshResponse) {
|
2016-12-15 08:47:31 +00:00
|
|
|
// Add the 'rocket' server header, and write out the response.
|
|
|
|
// TODO: If removing Hyper, write out `Data` header too.
|
|
|
|
response.set_header(header::Server("rocket".to_string()));
|
|
|
|
|
|
|
|
match self.write_response(response, hyp_res) {
|
|
|
|
Ok(_) => info_!("{}", Green.paint("Response succeeded.")),
|
|
|
|
Err(e) => error_!("Failed to write response: {:?}.", e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn write_response(&self, mut response: Response,
|
2016-12-15 17:24:29 +00:00
|
|
|
mut hyp_res: hyper::FreshResponse) -> io::Result<()>
|
2016-12-15 08:47:31 +00:00
|
|
|
{
|
|
|
|
*hyp_res.status_mut() = hyper::StatusCode::from_u16(response.status().code);
|
|
|
|
|
|
|
|
for header in response.headers() {
|
|
|
|
let name = header.name.into_owned();
|
|
|
|
let value = vec![header.value.into_owned().into()];
|
|
|
|
hyp_res.headers_mut().set_raw(name, value);
|
|
|
|
}
|
|
|
|
|
|
|
|
if response.body().is_none() {
|
|
|
|
hyp_res.headers_mut().set(header::ContentLength(0));
|
|
|
|
return hyp_res.start()?.end();
|
|
|
|
}
|
|
|
|
|
|
|
|
match response.body() {
|
|
|
|
None => {
|
|
|
|
hyp_res.headers_mut().set(header::ContentLength(0));
|
|
|
|
hyp_res.start()?.end()
|
|
|
|
}
|
|
|
|
Some(Body::Sized(mut body, size)) => {
|
|
|
|
hyp_res.headers_mut().set(header::ContentLength(size));
|
|
|
|
let mut stream = hyp_res.start()?;
|
|
|
|
io::copy(body, &mut stream)?;
|
|
|
|
stream.end()
|
|
|
|
}
|
|
|
|
Some(Body::Chunked(mut body, chunk_size)) => {
|
|
|
|
// This _might_ happen on a 32-bit machine!
|
|
|
|
if chunk_size > (usize::max_value() as u64) {
|
|
|
|
let msg = "chunk size exceeds limits of usize type";
|
|
|
|
return Err(io::Error::new(io::ErrorKind::Other, msg));
|
|
|
|
}
|
|
|
|
|
|
|
|
// The buffer stores the current chunk being written out.
|
|
|
|
let mut buffer = vec![0; chunk_size as usize];
|
|
|
|
let mut stream = hyp_res.start()?;
|
|
|
|
loop {
|
|
|
|
match body.read_max(&mut buffer)? {
|
|
|
|
0 => break,
|
|
|
|
n => stream.write_all(&buffer[..n])?,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
stream.end()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-10-16 10:21:34 +00:00
|
|
|
/// Preprocess the request for Rocket-specific things. At this time, we're
|
|
|
|
/// only checking for _method in forms.
|
|
|
|
fn preprocess_request(&self, req: &mut Request, data: &Data) {
|
|
|
|
// Check if this is a form and if the form contains the special _method
|
|
|
|
// field which we use to reinterpret the request's method.
|
|
|
|
let data_len = data.peek().len();
|
|
|
|
let (min_len, max_len) = ("_method=get".len(), "_method=delete".len());
|
|
|
|
if req.content_type().is_form() && data_len >= min_len {
|
|
|
|
let form = unsafe {
|
|
|
|
from_utf8_unchecked(&data.peek()[..min(data_len, max_len)])
|
|
|
|
};
|
|
|
|
|
|
|
|
let mut form_items = FormItems(form);
|
|
|
|
if let Some(("_method", value)) = form_items.next() {
|
|
|
|
if let Ok(method) = value.parse() {
|
2016-12-16 11:07:23 +00:00
|
|
|
req.set_method(method);
|
2016-10-16 10:21:34 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-12-16 13:17:16 +00:00
|
|
|
#[doc(hidden)]
|
2016-12-20 00:51:59 +00:00
|
|
|
#[inline(always)]
|
2016-12-16 13:17:16 +00:00
|
|
|
pub fn dispatch<'r>(&self, request: &'r mut Request, data: Data) -> Response<'r> {
|
|
|
|
// Do a bit of preprocessing before routing.
|
|
|
|
self.preprocess_request(request, &data);
|
|
|
|
|
|
|
|
// Route the request to get a response.
|
|
|
|
match self.route(request, data) {
|
|
|
|
Outcome::Success(mut response) => {
|
|
|
|
let cookie_delta = request.cookies().delta();
|
2016-12-17 17:18:30 +00:00
|
|
|
if !cookie_delta.is_empty() {
|
2016-12-16 13:17:16 +00:00
|
|
|
response.adjoin_header(header::SetCookie(cookie_delta));
|
|
|
|
}
|
|
|
|
|
|
|
|
response
|
|
|
|
}
|
|
|
|
Outcome::Forward(data) => {
|
|
|
|
// Rust thinks `request` is still borrowed here, but it's
|
|
|
|
// obviously not (data has nothing to do with it), so we
|
|
|
|
// convince it to give us another mutable reference.
|
2016-12-20 00:51:59 +00:00
|
|
|
// FIXME: Pay the cost to copy Request into UnsafeCell? Pay the
|
|
|
|
// cost to use RefCell? Move the call to `issue_response` here
|
|
|
|
// to move Request and move directly into a RefCell?
|
2016-12-16 13:17:16 +00:00
|
|
|
let request: &'r mut Request = unsafe {
|
|
|
|
&mut *(request as *const Request as *mut Request)
|
|
|
|
};
|
|
|
|
|
|
|
|
if request.method() == Method::Head {
|
|
|
|
info_!("Autohandling {} request.", White.paint("HEAD"));
|
|
|
|
request.set_method(Method::Get);
|
|
|
|
let mut response = self.dispatch(request, data);
|
|
|
|
response.strip_body();
|
|
|
|
response
|
|
|
|
} else {
|
|
|
|
self.handle_error(Status::NotFound, request)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Outcome::Failure(status) => self.handle_error(status, request),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
/// Tries to find a `Responder` for a given `request`. It does this by
|
|
|
|
/// routing the request and calling the handler for each matching route
|
|
|
|
/// until one of the handlers returns success or failure. If a handler
|
|
|
|
/// returns a failure, or there are no matching handlers willing to accept
|
|
|
|
/// the request, this function returns an `Err` with the status code.
|
2016-10-16 10:16:16 +00:00
|
|
|
#[doc(hidden)]
|
2016-12-20 00:51:59 +00:00
|
|
|
#[inline(always)]
|
2016-12-16 13:17:16 +00:00
|
|
|
pub fn route<'r>(&self, request: &'r Request, mut data: Data)
|
|
|
|
-> handler::Outcome<'r> {
|
2016-10-16 07:03:08 +00:00
|
|
|
// Go through the list of matching routes until we fail or succeed.
|
2016-10-16 10:16:16 +00:00
|
|
|
info!("{}:", request);
|
2016-12-17 17:18:30 +00:00
|
|
|
let matches = self.router.route(request);
|
2016-08-27 04:34:28 +00:00
|
|
|
for route in matches {
|
2016-08-26 08:55:11 +00:00
|
|
|
// Retrieve and set the requests parameters.
|
2016-08-27 04:34:28 +00:00
|
|
|
info_!("Matched: {}", route);
|
2016-12-16 23:14:11 +00:00
|
|
|
// FIXME: Users should not be able to use this.
|
2016-08-27 01:37:28 +00:00
|
|
|
request.set_params(route);
|
2016-08-26 08:55:11 +00:00
|
|
|
|
2016-10-08 06:20:49 +00:00
|
|
|
// Dispatch the request to the handler.
|
2016-12-17 17:18:30 +00:00
|
|
|
let outcome = (route.handler)(request, data);
|
2016-10-08 06:20:49 +00:00
|
|
|
|
|
|
|
// Check if the request processing completed or if the request needs
|
|
|
|
// to be forwarded. If it does, continue the loop to try again.
|
2016-12-15 08:47:31 +00:00
|
|
|
info_!("{} {}", White.paint("Outcome:"), outcome);
|
|
|
|
match outcome {
|
2016-12-17 17:18:30 +00:00
|
|
|
o@Outcome::Success(_) | o @Outcome::Failure(_) => return o,
|
2016-10-16 07:03:08 +00:00
|
|
|
Outcome::Forward(unused_data) => data = unused_data,
|
2016-08-27 04:34:28 +00:00
|
|
|
};
|
2016-04-11 10:57:23 +00:00
|
|
|
}
|
2016-08-27 04:34:28 +00:00
|
|
|
|
2016-12-15 08:47:31 +00:00
|
|
|
error_!("No matching routes for {}.", request);
|
2016-12-16 13:17:16 +00:00
|
|
|
Outcome::Forward(data)
|
2016-08-26 08:55:11 +00:00
|
|
|
}
|
2016-04-11 10:57:23 +00:00
|
|
|
|
2016-12-15 08:47:31 +00:00
|
|
|
// TODO: DOC.
|
2016-10-16 10:16:16 +00:00
|
|
|
#[doc(hidden)]
|
2016-12-15 08:47:31 +00:00
|
|
|
pub fn handle_error<'r>(&self, status: Status, req: &'r Request) -> Response<'r> {
|
|
|
|
warn_!("Responding with {} catcher.", Red.paint(&status));
|
2016-10-08 06:20:49 +00:00
|
|
|
|
2016-12-15 08:47:31 +00:00
|
|
|
// Try to get the active catcher but fallback to user's 500 catcher.
|
|
|
|
let catcher = self.catchers.get(&status.code).unwrap_or_else(|| {
|
|
|
|
error_!("No catcher found for {}. Using 500 catcher.", status);
|
|
|
|
self.catchers.get(&500).expect("500 catcher.")
|
|
|
|
});
|
2016-10-16 10:16:16 +00:00
|
|
|
|
2016-12-15 08:47:31 +00:00
|
|
|
// Dispatch to the user's catcher. If it fails, use the default 500.
|
|
|
|
let error = Error::NoRoute;
|
|
|
|
catcher.handle(error, req).unwrap_or_else(|err_status| {
|
|
|
|
error_!("Catcher failed with status: {}!", err_status);
|
|
|
|
warn_!("Using default 500 error catcher.");
|
|
|
|
let default = self.default_catchers.get(&500).expect("Default 500");
|
|
|
|
default.handle(error, req).expect("Default 500 response.")
|
|
|
|
})
|
2016-04-11 10:57:23 +00:00
|
|
|
}
|
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
/// 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 are used. See the
|
|
|
|
/// [config](/rocket/config/index.html) documentation for more information
|
|
|
|
/// on defaults.
|
|
|
|
///
|
|
|
|
/// This method is typically called through the `rocket::ignite` alias.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// If there is an error parsing the `Rocket.toml` file, this functions
|
|
|
|
/// prints a nice error message and then exits the process.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # {
|
|
|
|
/// rocket::ignite()
|
|
|
|
/// # };
|
|
|
|
/// ```
|
|
|
|
pub fn ignite() -> Rocket {
|
|
|
|
// Note: init() will exit the process under config errors.
|
|
|
|
let (config, initted) = config::init();
|
|
|
|
if initted {
|
|
|
|
logger::init(config.log_level);
|
|
|
|
}
|
|
|
|
|
|
|
|
Rocket::custom(config)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Creates a new `Rocket` application using the supplied custom
|
2016-11-11 22:04:00 +00:00
|
|
|
/// configuration information. Ignores the `Rocket.toml` file. Does not
|
|
|
|
/// enable logging. To enable logging, use the hidden
|
|
|
|
/// `logger::init(LoggingLevel)` method.
|
2016-11-04 13:35:04 +00:00
|
|
|
///
|
|
|
|
/// This method is typically called through the `rocket::custom` alias.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use rocket::config::{Config, Environment};
|
|
|
|
/// # use rocket::config::ConfigError;
|
|
|
|
///
|
|
|
|
/// # fn try_config() -> Result<(), ConfigError> {
|
|
|
|
/// let config = Config::default_for(Environment::active()?, "/custom")?
|
|
|
|
/// .address("1.2.3.4".into())
|
|
|
|
/// .port(9234);
|
|
|
|
///
|
|
|
|
/// let app = rocket::custom(&config);
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
pub fn custom(config: &Config) -> Rocket {
|
|
|
|
info!("🔧 Configured for {}.", config.env);
|
|
|
|
info_!("listening: {}:{}",
|
|
|
|
White.paint(&config.address),
|
|
|
|
White.paint(&config.port));
|
|
|
|
info_!("logging: {:?}", White.paint(config.log_level));
|
|
|
|
info_!("session key: {}", White.paint(config.take_session_key().is_some()));
|
|
|
|
for (name, value) in config.extras() {
|
|
|
|
info_!("{} {}: {}", Yellow.paint("[extra]"), name, White.paint(value));
|
|
|
|
}
|
|
|
|
|
|
|
|
Rocket {
|
|
|
|
address: config.address.clone(),
|
|
|
|
port: config.port,
|
|
|
|
router: Router::new(),
|
|
|
|
default_catchers: catcher::defaults::get(),
|
|
|
|
catchers: catcher::defaults::get(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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`.
|
|
|
|
///
|
|
|
|
/// # 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.
|
|
|
|
///
|
2016-12-17 18:51:44 +00:00
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// The `base` mount point must be a static path. That is, the mount point
|
|
|
|
/// must _not_ contain dynamic path parameters: `<param>`.
|
|
|
|
///
|
2016-11-04 13:35:04 +00:00
|
|
|
/// ```rust
|
|
|
|
/// # #![feature(plugin)]
|
|
|
|
/// # #![plugin(rocket_codegen)]
|
|
|
|
/// # extern crate rocket;
|
|
|
|
/// #
|
|
|
|
/// #[get("/world")]
|
|
|
|
/// fn hi() -> &'static str {
|
|
|
|
/// "Hello!"
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// # if false { // We don't actually want to launch the server in an example.
|
|
|
|
/// rocket::ignite().mount("/hello", routes![hi])
|
|
|
|
/// # .launch()
|
|
|
|
/// # }
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// 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.
|
|
|
|
///
|
|
|
|
/// ```rust
|
2016-12-15 08:47:31 +00:00
|
|
|
/// use rocket::{Request, Route, Data};
|
|
|
|
/// use rocket::handler::Outcome;
|
2016-11-04 13:35:04 +00:00
|
|
|
/// use rocket::http::Method::*;
|
|
|
|
///
|
2016-12-16 11:07:23 +00:00
|
|
|
/// fn hi(_: &Request, _: Data) -> Outcome<'static> {
|
2016-12-15 08:47:31 +00:00
|
|
|
/// Outcome::of("Hello!")
|
2016-11-04 13:35:04 +00:00
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// # if false { // We don't actually want to launch the server in an example.
|
|
|
|
/// rocket::ignite().mount("/hello", vec![Route::new(Get, "/world", hi)])
|
2016-11-04 14:11:59 +00:00
|
|
|
/// # .launch()
|
2016-11-04 13:35:04 +00:00
|
|
|
/// # }
|
|
|
|
/// ```
|
2016-10-08 11:42:22 +00:00
|
|
|
pub fn mount(mut self, base: &str, routes: Vec<Route>) -> Self {
|
2016-08-24 08:30:09 +00:00
|
|
|
info!("🛰 {} '{}':", Magenta.paint("Mounting"), base);
|
2016-12-17 18:51:44 +00:00
|
|
|
|
|
|
|
if base.contains('<') {
|
|
|
|
error_!("Bad mount point: '{}'.", base);
|
|
|
|
error_!("Mount points must be static paths!");
|
|
|
|
panic!("Bad mount point.")
|
|
|
|
}
|
|
|
|
|
2016-04-02 07:51:40 +00:00
|
|
|
for mut route in routes {
|
2016-10-18 02:29:58 +00:00
|
|
|
let path = format!("{}/{}", base, route.path.as_uri());
|
2016-04-02 07:51:40 +00:00
|
|
|
route.set_path(path);
|
|
|
|
|
2016-08-24 08:30:09 +00:00
|
|
|
info_!("{}", route);
|
2016-04-02 07:51:40 +00:00
|
|
|
self.router.add(route);
|
2016-04-01 23:54:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
/// Registers all of the catchers in the supplied vector.
|
2016-11-05 18:35:21 +00:00
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// #![feature(plugin)]
|
|
|
|
/// #![plugin(rocket_codegen)]
|
|
|
|
///
|
|
|
|
/// extern crate rocket;
|
|
|
|
///
|
|
|
|
/// use rocket::Request;
|
|
|
|
///
|
|
|
|
/// #[error(500)]
|
|
|
|
/// fn internal_error() -> &'static str {
|
|
|
|
/// "Whoops! Looks like we messed up."
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// #[error(400)]
|
|
|
|
/// fn not_found(req: &Request) -> String {
|
|
|
|
/// format!("I couldn't find '{}'. Try something else?", req.uri())
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// # if false { // We don't actually want to launch the server in an example.
|
|
|
|
/// rocket::ignite().catch(errors![internal_error, not_found])
|
|
|
|
/// # .launch()
|
|
|
|
/// # }
|
|
|
|
/// }
|
|
|
|
/// ```
|
2016-10-04 02:48:33 +00:00
|
|
|
pub fn catch(mut self, catchers: Vec<Catcher>) -> Self {
|
2016-08-24 08:30:09 +00:00
|
|
|
info!("👾 {}:", Magenta.paint("Catchers"));
|
2016-04-06 20:50:02 +00:00
|
|
|
for c in catchers {
|
2016-10-12 07:14:42 +00:00
|
|
|
if self.catchers.get(&c.code).map_or(false, |e| !e.is_default()) {
|
|
|
|
let msg = "(warning: duplicate catcher!)";
|
|
|
|
info_!("{} {}", c, Yellow.paint(msg));
|
2016-04-06 20:50:02 +00:00
|
|
|
} else {
|
2016-08-24 08:30:09 +00:00
|
|
|
info_!("{}", c);
|
2016-04-06 20:50:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self.catchers.insert(c.code, c);
|
2016-04-06 10:26:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2016-11-04 13:35:04 +00:00
|
|
|
/// Starts the application server and begins listening for and dispatching
|
|
|
|
/// requests to mounted routes and catchers.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// If the server could not be started, this method prints the reason and
|
|
|
|
/// then exits the process.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # if false {
|
|
|
|
/// rocket::ignite().launch()
|
|
|
|
/// # }
|
|
|
|
/// ```
|
2016-10-04 02:37:49 +00:00
|
|
|
pub fn launch(self) {
|
2016-04-01 23:54:53 +00:00
|
|
|
if self.router.has_collisions() {
|
2016-08-24 08:30:09 +00:00
|
|
|
warn!("Route collisions detected!");
|
2016-04-01 23:54:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let full_addr = format!("{}:{}", self.address, self.port);
|
2016-12-15 17:24:29 +00:00
|
|
|
let server = match hyper::Server::http(full_addr.as_str()) {
|
2016-10-03 10:39:56 +00:00
|
|
|
Ok(hyper_server) => hyper_server,
|
|
|
|
Err(e) => {
|
2016-12-17 18:51:44 +00:00
|
|
|
error!("Failed to start server.");
|
|
|
|
panic!("{}", e);
|
2016-10-03 10:39:56 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
2016-09-30 22:20:11 +00:00
|
|
|
info!("🚀 {} {}...",
|
|
|
|
White.paint("Rocket has launched from"),
|
|
|
|
White.bold().paint(&full_addr));
|
2016-10-03 10:39:56 +00:00
|
|
|
|
|
|
|
server.handle(self).unwrap();
|
2016-04-01 23:54:53 +00:00
|
|
|
}
|
|
|
|
}
|