mirror of https://github.com/rwf2/Rocket.git
Reform top-level libs mostly according to Rustfmt.
This commit is contained in:
parent
008605bec7
commit
a29d56c52e
|
@ -11,6 +11,5 @@ pub struct StaticRouteInfo {
|
||||||
|
|
||||||
pub struct StaticCatchInfo {
|
pub struct StaticCatchInfo {
|
||||||
pub code: u16,
|
pub code: u16,
|
||||||
pub handler: ErrorHandler
|
pub handler: ErrorHandler,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
pub use response::mime::{Mime, TopLevel, SubLevel};
|
pub use response::mime::{Mime, TopLevel, SubLevel};
|
||||||
use response::mime::{Param};
|
use response::mime::Param;
|
||||||
use std::default::Default;
|
use std::default::Default;
|
||||||
|
|
||||||
use std::str::FromStr;
|
use std::str::FromStr;
|
||||||
|
@ -105,7 +105,7 @@ impl From<Mime> for ContentType {
|
||||||
fn from(mime: Mime) -> ContentType {
|
fn from(mime: Mime) -> ContentType {
|
||||||
let params = match mime.2.len() {
|
let params = match mime.2.len() {
|
||||||
0 => None,
|
0 => None,
|
||||||
_ => Some(mime.2)
|
_ => Some(mime.2),
|
||||||
};
|
};
|
||||||
|
|
||||||
ContentType(mime.0, mime.1, params)
|
ContentType(mime.0, mime.1, params)
|
||||||
|
@ -115,14 +115,14 @@ impl From<Mime> for ContentType {
|
||||||
fn is_valid_first_char(c: char) -> bool {
|
fn is_valid_first_char(c: char) -> bool {
|
||||||
match c {
|
match c {
|
||||||
'a'...'z' | 'A'...'Z' | '0'...'9' | '*' => true,
|
'a'...'z' | 'A'...'Z' | '0'...'9' | '*' => true,
|
||||||
_ => false
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_valid_char(c: char) -> bool {
|
fn is_valid_char(c: char) -> bool {
|
||||||
is_valid_first_char(c) || match c {
|
is_valid_first_char(c) || match c {
|
||||||
'!' | '#' | '$' | '&' | '-' | '^' | '.' | '+' | '_' => true,
|
'!' | '#' | '$' | '&' | '-' | '^' | '.' | '+' | '_' => true,
|
||||||
_ => false
|
_ => false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -132,33 +132,34 @@ impl FromStr for ContentType {
|
||||||
fn from_str(raw: &str) -> Result<ContentType, &'static str> {
|
fn from_str(raw: &str) -> Result<ContentType, &'static str> {
|
||||||
let slash = match raw.find('/') {
|
let slash = match raw.find('/') {
|
||||||
Some(i) => i,
|
Some(i) => i,
|
||||||
None => return Err("Missing / in MIME type.")
|
None => return Err("Missing / in MIME type."),
|
||||||
};
|
};
|
||||||
|
|
||||||
let top_str = &raw[..slash];
|
let top_s = &raw[..slash];
|
||||||
let (sub_str, _rest) = match raw.find(';') {
|
let (sub_s, _rest) = match raw.find(';') {
|
||||||
Some(j) => (&raw[(slash + 1)..j], Some(&raw[(j + 1)..])),
|
Some(j) => (&raw[(slash + 1)..j], Some(&raw[(j + 1)..])),
|
||||||
None => (&raw[(slash + 1)..], None)
|
None => (&raw[(slash + 1)..], None),
|
||||||
};
|
};
|
||||||
|
|
||||||
if top_str.len() < 1 || sub_str.len() < 1 {
|
if top_s.len() < 1 || sub_s.len() < 1 {
|
||||||
return Err("Empty string.")
|
return Err("Empty string.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if !is_valid_first_char(top_str.chars().next().unwrap())
|
if !is_valid_first_char(top_s.chars().next().unwrap())
|
||||||
|| !is_valid_first_char(sub_str.chars().next().unwrap()) {
|
|| !is_valid_first_char(sub_s.chars().next().unwrap()) {
|
||||||
return Err("Invalid first char.")
|
return Err("Invalid first char.");
|
||||||
}
|
}
|
||||||
|
|
||||||
if top_str.contains(|c| !is_valid_char(c))
|
if top_s.contains(|c| !is_valid_char(c))
|
||||||
|| sub_str.contains(|c| !is_valid_char(c)) {
|
|| sub_s.contains(|c| !is_valid_char(c)) {
|
||||||
return Err("Invalid character in string.")
|
return Err("Invalid character in string.");
|
||||||
}
|
}
|
||||||
|
|
||||||
let (top_str, sub_str) = (&*top_str.to_lowercase(), &*sub_str.to_lowercase());
|
let (top_s, sub_s) = (&*top_s.to_lowercase(), &*sub_s.to_lowercase());
|
||||||
let top_level = TopLevel::from_str(top_str).map_err(|_| "Bad TopLevel")?;
|
let top_level = TopLevel::from_str(top_s).map_err(|_| "Bad TopLevel")?;
|
||||||
let sub_level = SubLevel::from_str(sub_str).map_err(|_| "Bad SubLevel")?;
|
let sub_level = SubLevel::from_str(sub_s).map_err(|_| "Bad SubLevel")?;
|
||||||
// FIXME: Use `rest` to find params.
|
|
||||||
|
// FIXME: Use `rest` to find params.
|
||||||
Ok(ContentType::new(top_level, sub_level, None))
|
Ok(ContentType::new(top_level, sub_level, None))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -186,17 +187,13 @@ impl Collider for ContentType {
|
||||||
|
|
||||||
impl Collider for TopLevel {
|
impl Collider for TopLevel {
|
||||||
fn collides_with(&self, other: &TopLevel) -> bool {
|
fn collides_with(&self, other: &TopLevel) -> bool {
|
||||||
*self == TopLevel::Star
|
*self == TopLevel::Star || *other == TopLevel::Star || *self == *other
|
||||||
|| *other == TopLevel::Star
|
|
||||||
|| *self == *other
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Collider for SubLevel {
|
impl Collider for SubLevel {
|
||||||
fn collides_with(&self, other: &SubLevel) -> bool {
|
fn collides_with(&self, other: &SubLevel) -> bool {
|
||||||
*self == SubLevel::Star
|
*self == SubLevel::Star || *other == SubLevel::Star || *self == *other
|
||||||
|| *other == SubLevel::Star
|
|
||||||
|| *self == *other
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -4,5 +4,5 @@ pub enum Error {
|
||||||
BadParse,
|
BadParse,
|
||||||
NoRoute, // FIXME: Add a chain of routes attempted.
|
NoRoute, // FIXME: Add a chain of routes attempted.
|
||||||
Internal,
|
Internal,
|
||||||
NoKey
|
NoKey,
|
||||||
}
|
}
|
||||||
|
|
|
@ -118,6 +118,7 @@ pub trait FromFormValue<'v>: Sized {
|
||||||
impl<'v> FromFormValue<'v> for &'v str {
|
impl<'v> FromFormValue<'v> for &'v str {
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
|
||||||
|
// This just gives the raw string.
|
||||||
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
|
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
|
||||||
Ok(v)
|
Ok(v)
|
||||||
}
|
}
|
||||||
|
@ -154,7 +155,7 @@ impl<'v> FromFormValue<'v> for bool {
|
||||||
match v {
|
match v {
|
||||||
"on" | "true" => Ok(true),
|
"on" | "true" => Ok(true),
|
||||||
"off" | "false" => Ok(false),
|
"off" | "false" => Ok(false),
|
||||||
_ => Err(v)
|
_ => Err(v),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -179,7 +180,7 @@ impl<'v, T: FromFormValue<'v>> FromFormValue<'v> for Option<T> {
|
||||||
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
|
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
|
||||||
match T::from_form_value(v) {
|
match T::from_form_value(v) {
|
||||||
Ok(v) => Ok(Some(v)),
|
Ok(v) => Ok(Some(v)),
|
||||||
Err(_) => Ok(None)
|
Err(_) => Ok(None),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -195,7 +196,7 @@ impl<'v, T: FromFormValue<'v>> FromFormValue<'v> for Result<T, T::Error> {
|
||||||
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
|
fn from_form_value(v: &'v str) -> Result<Self, Self::Error> {
|
||||||
match T::from_form_value(v) {
|
match T::from_form_value(v) {
|
||||||
ok@Ok(_) => Ok(ok),
|
ok@Ok(_) => Ok(ok),
|
||||||
e@Err(_) => Ok(e)
|
e@Err(_) => Ok(e),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -238,12 +239,12 @@ impl<'f> Iterator for FormItems<'f> {
|
||||||
let string = self.0;
|
let string = self.0;
|
||||||
let (key, rest) = match string.find('=') {
|
let (key, rest) = match string.find('=') {
|
||||||
Some(index) => (&string[..index], &string[(index + 1)..]),
|
Some(index) => (&string[..index], &string[(index + 1)..]),
|
||||||
None => return None
|
None => return None,
|
||||||
};
|
};
|
||||||
|
|
||||||
let (value, remainder) = match rest.find('&') {
|
let (value, remainder) = match rest.find('&') {
|
||||||
Some(index) => (&rest[..index], &rest[(index + 1)..]),
|
Some(index) => (&rest[..index], &rest[(index + 1)..]),
|
||||||
None => (rest, "")
|
None => (rest, ""),
|
||||||
};
|
};
|
||||||
|
|
||||||
self.0 = remainder;
|
self.0 = remainder;
|
||||||
|
|
|
@ -22,14 +22,11 @@ extern crate url;
|
||||||
extern crate mime;
|
extern crate mime;
|
||||||
#[macro_use] extern crate log;
|
#[macro_use] extern crate log;
|
||||||
|
|
||||||
#[doc(hidden)]
|
#[doc(hidden)] #[macro_use] pub mod logger;
|
||||||
#[macro_use]
|
#[doc(hidden)] pub mod content_type;
|
||||||
pub mod logger;
|
|
||||||
pub mod form;
|
pub mod form;
|
||||||
pub mod request;
|
pub mod request;
|
||||||
pub mod response;
|
pub mod response;
|
||||||
#[doc(hidden)]
|
|
||||||
pub mod content_type;
|
|
||||||
|
|
||||||
mod method;
|
mod method;
|
||||||
mod error;
|
mod error;
|
||||||
|
@ -49,17 +46,14 @@ pub mod handler {
|
||||||
pub type ErrorHandler = for<'r> fn(error: Error, &'r Request<'r>) -> Response<'r>;
|
pub type ErrorHandler = for<'r> fn(error: Error, &'r Request<'r>) -> Response<'r>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[doc(inline)] pub use response::{Response, Responder};
|
||||||
|
#[doc(inline)] pub use handler::{Handler, ErrorHandler};
|
||||||
|
#[doc(inline)] pub use logger::LoggingLevel;
|
||||||
pub use content_type::ContentType;
|
pub use content_type::ContentType;
|
||||||
pub use codegen::{StaticRouteInfo, StaticCatchInfo};
|
pub use codegen::{StaticRouteInfo, StaticCatchInfo};
|
||||||
pub use request::Request;
|
pub use request::Request;
|
||||||
pub use method::Method;
|
pub use method::Method;
|
||||||
#[doc(inline)]
|
|
||||||
pub use response::{Response, Responder};
|
|
||||||
pub use error::Error;
|
pub use error::Error;
|
||||||
pub use router::{Router, Route};
|
pub use router::{Router, Route};
|
||||||
pub use catcher::Catcher;
|
pub use catcher::Catcher;
|
||||||
pub use rocket::Rocket;
|
pub use rocket::Rocket;
|
||||||
#[doc(inline)]
|
|
||||||
pub use handler::{Handler, ErrorHandler};
|
|
||||||
#[doc(inline)]
|
|
||||||
pub use logger::LoggingLevel;
|
|
||||||
|
|
|
@ -23,7 +23,7 @@ impl LoggingLevel {
|
||||||
match *self {
|
match *self {
|
||||||
LoggingLevel::Critical => LogLevel::Warn,
|
LoggingLevel::Critical => LogLevel::Warn,
|
||||||
LoggingLevel::Normal => LogLevel::Info,
|
LoggingLevel::Normal => LogLevel::Info,
|
||||||
LoggingLevel::Debug => LogLevel::Trace
|
LoggingLevel::Debug => LogLevel::Trace,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -31,7 +31,7 @@ impl Method {
|
||||||
HyperMethod::Trace => Some(Trace),
|
HyperMethod::Trace => Some(Trace),
|
||||||
HyperMethod::Connect => Some(Connect),
|
HyperMethod::Connect => Some(Connect),
|
||||||
HyperMethod::Patch => Some(Patch),
|
HyperMethod::Patch => Some(Patch),
|
||||||
HyperMethod::Extension(_) => None
|
HyperMethod::Extension(_) => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -46,7 +46,7 @@ impl<'r, 'c, T: FromRequest<'r, 'c>> FromRequest<'r, 'c> for Option<T> {
|
||||||
fn from_request(request: &'r Request<'c>) -> Result<Self, Self::Error> {
|
fn from_request(request: &'r Request<'c>) -> Result<Self, Self::Error> {
|
||||||
let opt = match T::from_request(request) {
|
let opt = match T::from_request(request) {
|
||||||
Ok(v) => Some(v),
|
Ok(v) => Some(v),
|
||||||
Err(_) => None
|
Err(_) => None,
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(opt)
|
Ok(opt)
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
use std::io::{Read};
|
use std::io::Read;
|
||||||
use std::cell::RefCell;
|
use std::cell::RefCell;
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
|
@ -45,8 +45,9 @@ impl<'a> Request<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
/// i is the index of the first segment to consider
|
/// i is the index of the first segment to consider
|
||||||
pub fn get_segments<'r: 'a, T: FromSegments<'a>>(&'r self, i: usize)
|
pub fn get_segments<'r: 'a, T: FromSegments<'a>>(&'r self,
|
||||||
-> Result<T, Error> {
|
i: usize)
|
||||||
|
-> Result<T, Error> {
|
||||||
if i >= self.uri().segment_count() {
|
if i >= self.uri().segment_count() {
|
||||||
debug!("{} is >= segment count {}", i, self.uri().segment_count());
|
debug!("{} is >= segment count {}", i, self.uri().segment_count());
|
||||||
Err(Error::NoKey)
|
Err(Error::NoKey)
|
||||||
|
@ -55,6 +56,7 @@ impl<'a> Request<'a> {
|
||||||
// but the std lib doesn't implement it for Skip.
|
// but the std lib doesn't implement it for Skip.
|
||||||
let mut segments = self.uri.segments();
|
let mut segments = self.uri.segments();
|
||||||
for _ in segments.by_ref().take(i) { /* do nothing */ }
|
for _ in segments.by_ref().take(i) { /* do nothing */ }
|
||||||
|
|
||||||
T::from_segments(segments).map_err(|_| Error::BadParse)
|
T::from_segments(segments).map_err(|_| Error::BadParse)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -66,7 +68,7 @@ impl<'a> Request<'a> {
|
||||||
cookies: Cookies::new(&[]),
|
cookies: Cookies::new(&[]),
|
||||||
uri: URIBuf::from(uri),
|
uri: URIBuf::from(uri),
|
||||||
data: vec![],
|
data: vec![],
|
||||||
headers: HyperHeaders::new()
|
headers: HyperHeaders::new(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -90,7 +92,7 @@ impl<'a> Request<'a> {
|
||||||
if items.len() < 1 {
|
if items.len() < 1 {
|
||||||
return ContentType::any();
|
return ContentType::any();
|
||||||
} else {
|
} else {
|
||||||
return ContentType::from(items[0].item.clone())
|
return ContentType::from(items[0].item.clone());
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
@ -111,23 +113,23 @@ impl<'a> Request<'a> {
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_hyp<'h, 'k>(hyper_req: HyperRequest<'h, 'k>)
|
pub fn from_hyp<'h, 'k>(hyper_req: HyperRequest<'h, 'k>)
|
||||||
-> Result<Request<'a>, String> {
|
-> Result<Request<'a>, String> {
|
||||||
let (_, h_method, h_headers, h_uri, _, mut h_body) = hyper_req.deconstruct();
|
let (_, h_method, h_headers, h_uri, _, mut h_body) = hyper_req.deconstruct();
|
||||||
|
|
||||||
let uri = match h_uri {
|
let uri = match h_uri {
|
||||||
HyperRequestUri::AbsolutePath(s) => URIBuf::from(s),
|
HyperRequestUri::AbsolutePath(s) => URIBuf::from(s),
|
||||||
_ => return Err(format!("Bad URI: {}", h_uri))
|
_ => return Err(format!("Bad URI: {}", h_uri)),
|
||||||
};
|
};
|
||||||
|
|
||||||
let method = match Method::from_hyp(&h_method) {
|
let method = match Method::from_hyp(&h_method) {
|
||||||
Some(m) => m,
|
Some(m) => m,
|
||||||
_ => return Err(format!("Bad method: {}", h_method))
|
_ => return Err(format!("Bad method: {}", h_method)),
|
||||||
};
|
};
|
||||||
|
|
||||||
let cookies = match h_headers.get::<HyperCookie>() {
|
let cookies = match h_headers.get::<HyperCookie>() {
|
||||||
// TODO: What to do about key?
|
// TODO: What to do about key?
|
||||||
Some(cookie) => cookie.to_cookie_jar(&[]),
|
Some(cookie) => cookie.to_cookie_jar(&[]),
|
||||||
None => Cookies::new(&[])
|
None => Cookies::new(&[]),
|
||||||
};
|
};
|
||||||
|
|
||||||
// FIXME: GRRR.
|
// FIXME: GRRR.
|
||||||
|
|
|
@ -8,7 +8,7 @@ const FLASH_COOKIE_NAME: &'static str = "_flash";
|
||||||
pub struct Flash<R> {
|
pub struct Flash<R> {
|
||||||
name: String,
|
name: String,
|
||||||
message: String,
|
message: String,
|
||||||
responder: R
|
responder: R,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Responder> Flash<R> {
|
impl<R: Responder> Flash<R> {
|
||||||
|
@ -89,7 +89,7 @@ impl<'r, 'c> FromRequest<'r, 'c> for Flash<()> {
|
||||||
let content = cookie.pair().1;
|
let content = cookie.pair().1;
|
||||||
let (len_str, rest) = match content.find(|c: char| !c.is_digit(10)) {
|
let (len_str, rest) = match content.find(|c: char| !c.is_digit(10)) {
|
||||||
Some(i) => (&content[..i], &content[i..]),
|
Some(i) => (&content[..i], &content[i..]),
|
||||||
None => (content, "")
|
None => (content, ""),
|
||||||
};
|
};
|
||||||
|
|
||||||
let name_len: usize = len_str.parse().map_err(|_| ())?;
|
let name_len: usize = len_str.parse().map_err(|_| ())?;
|
||||||
|
@ -98,4 +98,3 @@ impl<'r, 'c> FromRequest<'r, 'c> for Flash<()> {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -35,8 +35,9 @@ impl<'a> Response<'a> {
|
||||||
Response(Box::new(body))
|
Response(Box::new(body))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_status<T: Responder + 'a>(status: StatusCode, body: T)
|
pub fn with_status<T: Responder + 'a>(status: StatusCode,
|
||||||
-> Response<'a> {
|
body: T)
|
||||||
|
-> Response<'a> {
|
||||||
Response(Box::new(StatusResponse::new(status, body)))
|
Response(Box::new(StatusResponse::new(status, body)))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -44,8 +45,7 @@ impl<'a> Response<'a> {
|
||||||
Response(Box::new(Forward))
|
Response(Box::new(Forward))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn with_raw_status<T: Responder + 'a>(status: u16, body: T)
|
pub fn with_raw_status<T: Responder + 'a>(status: u16, body: T) -> Response<'a> {
|
||||||
-> Response<'a> {
|
|
||||||
let status_code = StatusCode::from_u16(status);
|
let status_code = StatusCode::from_u16(status);
|
||||||
Response(Box::new(StatusResponse::new(status_code, body)))
|
Response(Box::new(StatusResponse::new(status_code, body)))
|
||||||
}
|
}
|
||||||
|
|
|
@ -73,7 +73,9 @@ impl io::Write for NamedFile {
|
||||||
self.file().write(buf)
|
self.file().write(buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flush(&mut self) -> io::Result<()> { self.file().flush() }
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
self.file().flush()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl io::Seek for NamedFile {
|
impl io::Seek for NamedFile {
|
||||||
|
@ -97,7 +99,9 @@ impl<'a> io::Write for &'a NamedFile {
|
||||||
self.file().write(buf)
|
self.file().write(buf)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn flush(&mut self) -> io::Result<()> { self.file().flush() }
|
fn flush(&mut self) -> io::Result<()> {
|
||||||
|
self.file().flush()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> io::Seek for &'a NamedFile {
|
impl<'a> io::Seek for &'a NamedFile {
|
||||||
|
|
|
@ -50,18 +50,10 @@ impl<'h> fmt::Debug for Outcome<'h> {
|
||||||
impl<'h> fmt::Display for Outcome<'h> {
|
impl<'h> fmt::Display for Outcome<'h> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
match *self {
|
match *self {
|
||||||
Outcome::Complete => {
|
Outcome::Complete => write!(f, "{}", Green.paint("Complete")),
|
||||||
write!(f, "{}", Green.paint("Complete"))
|
Outcome::Bad(..) => write!(f, "{}", Yellow.paint("Bad Completion")),
|
||||||
},
|
Outcome::FailStop => write!(f, "{}", Red.paint("Failed")),
|
||||||
Outcome::Bad(..) => {
|
Outcome::FailForward(..) => write!(f, "{}", Cyan.paint("Forwarding")),
|
||||||
write!(f, "{}", Yellow.paint("Bad Completion"))
|
|
||||||
},
|
|
||||||
Outcome::FailStop => {
|
|
||||||
write!(f, "{}", Red.paint("Failed"))
|
|
||||||
},
|
|
||||||
Outcome::FailForward(..) => {
|
|
||||||
write!(f, "{}", Cyan.paint("Forwarding"))
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -34,4 +34,3 @@ impl<'a> Responder for Redirect {
|
||||||
Outcome::Complete
|
Outcome::Complete
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -69,8 +69,7 @@ impl<T: Responder> Responder for Option<T> {
|
||||||
|
|
||||||
impl<T: Responder, E: fmt::Debug> Responder for Result<T, E> {
|
impl<T: Responder, E: fmt::Debug> Responder for Result<T, E> {
|
||||||
// prepend with `default` when using impl specialization
|
// prepend with `default` when using impl specialization
|
||||||
default fn respond<'a>(&mut self, res: FreshHyperResponse<'a>)
|
default fn respond<'a>(&mut self, res: FreshHyperResponse<'a>) -> Outcome<'a> {
|
||||||
-> Outcome<'a> {
|
|
||||||
if self.is_err() {
|
if self.is_err() {
|
||||||
error_!("{:?}", self.as_ref().err().unwrap());
|
error_!("{:?}", self.as_ref().err().unwrap());
|
||||||
// TODO: Should this be a 404 or 500?
|
// TODO: Should this be a 404 or 500?
|
||||||
|
@ -85,7 +84,7 @@ impl<T: Responder, E: Responder + fmt::Debug> Responder for Result<T, E> {
|
||||||
fn respond<'a>(&mut self, res: FreshHyperResponse<'a>) -> Outcome<'a> {
|
fn respond<'a>(&mut self, res: FreshHyperResponse<'a>) -> Outcome<'a> {
|
||||||
match *self {
|
match *self {
|
||||||
Ok(ref mut responder) => responder.respond(res),
|
Ok(ref mut responder) => responder.respond(res),
|
||||||
Err(ref mut responder) => responder.respond(res)
|
Err(ref mut responder) => responder.respond(res),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -12,15 +12,15 @@ impl<T: Read> Stream<T> {
|
||||||
Stream(Box::new(reader))
|
Stream(Box::new(reader))
|
||||||
}
|
}
|
||||||
|
|
||||||
// pub fn chunked(mut self, size: usize) -> Self {
|
// pub fn chunked(mut self, size: usize) -> Self {
|
||||||
// self.1 = size;
|
// self.1 = size;
|
||||||
// self
|
// self
|
||||||
// }
|
// }
|
||||||
|
|
||||||
// #[inline(always)]
|
// #[inline(always)]
|
||||||
// pub fn chunk_size(&self) -> usize {
|
// pub fn chunk_size(&self) -> usize {
|
||||||
// self.1
|
// self.1
|
||||||
// }
|
// }
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Read> Responder for Stream<T> {
|
impl<T: Read> Responder for Stream<T> {
|
||||||
|
|
|
@ -2,14 +2,14 @@ use response::*;
|
||||||
|
|
||||||
pub struct StatusResponse<R: Responder> {
|
pub struct StatusResponse<R: Responder> {
|
||||||
status: StatusCode,
|
status: StatusCode,
|
||||||
responder: R
|
responder: R,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<R: Responder> StatusResponse<R> {
|
impl<R: Responder> StatusResponse<R> {
|
||||||
pub fn new(status: StatusCode, responder: R) -> StatusResponse<R> {
|
pub fn new(status: StatusCode, responder: R) -> StatusResponse<R> {
|
||||||
StatusResponse {
|
StatusResponse {
|
||||||
status: status,
|
status: status,
|
||||||
responder: responder
|
responder: responder,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -20,4 +20,3 @@ impl<R: Responder> Responder for StatusResponse<R> {
|
||||||
self.responder.respond(res)
|
self.responder.respond(res)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -23,15 +23,17 @@ pub struct Rocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl HyperHandler for Rocket {
|
impl HyperHandler for Rocket {
|
||||||
fn handle<'h, 'k>(&self, req: HyperRequest<'h, 'k>,
|
fn handle<'h, 'k>(&self,
|
||||||
mut res: FreshHyperResponse<'h>) {
|
req: HyperRequest<'h, 'k>,
|
||||||
|
mut res: FreshHyperResponse<'h>) {
|
||||||
res.headers_mut().set(response::header::Server("rocket".to_string()));
|
res.headers_mut().set(response::header::Server("rocket".to_string()));
|
||||||
self.dispatch(req, res)
|
self.dispatch(req, res)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Rocket {
|
impl Rocket {
|
||||||
fn dispatch<'h, 'k>(&self, hyp_req: HyperRequest<'h, 'k>,
|
fn dispatch<'h, 'k>(&self,
|
||||||
|
hyp_req: HyperRequest<'h, 'k>,
|
||||||
mut res: FreshHyperResponse<'h>) {
|
mut res: FreshHyperResponse<'h>) {
|
||||||
// Get a copy of the URI for later use.
|
// Get a copy of the URI for later use.
|
||||||
let uri = hyp_req.uri.to_string();
|
let uri = hyp_req.uri.to_string();
|
||||||
|
@ -41,7 +43,7 @@ impl Rocket {
|
||||||
Ok(mut req) => {
|
Ok(mut req) => {
|
||||||
self.preprocess_request(&mut req);
|
self.preprocess_request(&mut req);
|
||||||
req
|
req
|
||||||
},
|
}
|
||||||
Err(ref reason) => {
|
Err(ref reason) => {
|
||||||
let mock_request = Request::mock(Method::Get, uri.as_str());
|
let mock_request = Request::mock(Method::Get, uri.as_str());
|
||||||
debug_!("Bad request: {}", reason);
|
debug_!("Bad request: {}", reason);
|
||||||
|
@ -71,7 +73,7 @@ impl Rocket {
|
||||||
res = match outcome {
|
res = match outcome {
|
||||||
Outcome::Complete | Outcome::FailStop => return,
|
Outcome::Complete | Outcome::FailStop => return,
|
||||||
Outcome::FailForward(r) => r,
|
Outcome::FailForward(r) => r,
|
||||||
Outcome::Bad(r) => return self.handle_internal_error(&request, r)
|
Outcome::Bad(r) => return self.handle_internal_error(&request, r),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -101,15 +103,17 @@ impl Rocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call on internal server error.
|
// Call on internal server error.
|
||||||
fn handle_internal_error<'r>(&self, request: &'r Request<'r>,
|
fn handle_internal_error<'r>(&self,
|
||||||
response: FreshHyperResponse) {
|
request: &'r Request<'r>,
|
||||||
|
response: FreshHyperResponse) {
|
||||||
error_!("Internal server error.");
|
error_!("Internal server error.");
|
||||||
let catcher = self.catchers.get(&500).unwrap();
|
let catcher = self.catchers.get(&500).unwrap();
|
||||||
catcher.handle(Error::Internal, request).respond(response);
|
catcher.handle(Error::Internal, request).respond(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Call when no route was found.
|
// Call when no route was found.
|
||||||
fn handle_not_found<'r>(&self, request: &'r Request<'r>,
|
fn handle_not_found<'r>(&self,
|
||||||
|
request: &'r Request<'r>,
|
||||||
response: FreshHyperResponse) {
|
response: FreshHyperResponse) {
|
||||||
error_!("{} dispatch failed: 404.", request);
|
error_!("{} dispatch failed: 404.", request);
|
||||||
let catcher = self.catchers.get(&404).unwrap();
|
let catcher = self.catchers.get(&404).unwrap();
|
||||||
|
@ -126,8 +130,7 @@ impl Rocket {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn mount(&mut self, base: &'static str, routes: Vec<Route>)
|
pub fn mount(&mut self, base: &'static str, routes: Vec<Route>) -> &mut Self {
|
||||||
-> &mut Self {
|
|
||||||
self.enable_normal_logging_if_disabled();
|
self.enable_normal_logging_if_disabled();
|
||||||
info!("🛰 {} '{}':", Magenta.paint("Mounting"), base);
|
info!("🛰 {} '{}':", Magenta.paint("Mounting"), base);
|
||||||
for mut route in routes {
|
for mut route in routes {
|
||||||
|
@ -190,8 +193,9 @@ impl Rocket {
|
||||||
}
|
}
|
||||||
|
|
||||||
let full_addr = format!("{}:{}", self.address, self.port);
|
let full_addr = format!("{}:{}", self.address, self.port);
|
||||||
info!("🚀 {} {}...", White.paint("Rocket has launched from"),
|
info!("🚀 {} {}...",
|
||||||
White.bold().paint(&full_addr));
|
White.paint("Rocket has launched from"),
|
||||||
|
White.bold().paint(&full_addr));
|
||||||
let _ = HyperServer::http(full_addr.as_str()).unwrap().handle(self);
|
let _ = HyperServer::http(full_addr.as_str()).unwrap().handle(self);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -5,8 +5,11 @@ pub trait Collider<T: ?Sized = Self> {
|
||||||
fn collides_with(&self, other: &T) -> bool;
|
fn collides_with(&self, other: &T) -> bool;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn index_match_until(break_c: char, a: &str, b: &str, dir: bool)
|
pub fn index_match_until(break_c: char,
|
||||||
-> Option<(isize, isize)> {
|
a: &str,
|
||||||
|
b: &str,
|
||||||
|
dir: bool)
|
||||||
|
-> Option<(isize, isize)> {
|
||||||
let (a_len, b_len) = (a.len() as isize, b.len() as isize);
|
let (a_len, b_len) = (a.len() as isize, b.len() as isize);
|
||||||
let (mut i, mut j, delta) = if dir {
|
let (mut i, mut j, delta) = if dir {
|
||||||
(0, 0, 1)
|
(0, 0, 1)
|
||||||
|
|
|
@ -15,7 +15,7 @@ type Selector = Method;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct Router {
|
pub struct Router {
|
||||||
routes: HashMap<Selector, Vec<Route>> // using 'selector' for now
|
routes: HashMap<Selector, Vec<Route>>, // using 'selector' for now
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Router {
|
impl Router {
|
||||||
|
@ -39,9 +39,9 @@ impl Router {
|
||||||
// let num_segments = req.uri.segment_count();
|
// let num_segments = req.uri.segment_count();
|
||||||
// self.routes.get(&(req.method, num_segments)).map_or(vec![], |routes| {
|
// self.routes.get(&(req.method, num_segments)).map_or(vec![], |routes| {
|
||||||
self.routes.get(&req.method).map_or(vec![], |routes| {
|
self.routes.get(&req.method).map_or(vec![], |routes| {
|
||||||
let mut matches: Vec<_> = routes.iter().filter(|r| {
|
let mut matches: Vec<_> = routes.iter()
|
||||||
r.collides_with(req)
|
.filter(|r| r.collides_with(req))
|
||||||
}).collect();
|
.collect();
|
||||||
|
|
||||||
matches.sort_by(|a, b| a.rank.cmp(&b.rank));
|
matches.sort_by(|a, b| a.rank.cmp(&b.rank));
|
||||||
trace_!("All matches: {:?}", matches);
|
trace_!("All matches: {:?}", matches);
|
||||||
|
@ -149,7 +149,10 @@ mod test {
|
||||||
assert!(!default_rank_route_collisions(&["/a/b", "/a/b/<c..>"]));
|
assert!(!default_rank_route_collisions(&["/a/b", "/a/b/<c..>"]));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn route<'a>(router: &'a Router, method: Method, uri: &str) -> Option<&'a Route> {
|
fn route<'a>(router: &'a Router,
|
||||||
|
method: Method,
|
||||||
|
uri: &str)
|
||||||
|
-> Option<&'a Route> {
|
||||||
let request = Request::mock(method, uri);
|
let request = Request::mock(method, uri);
|
||||||
let matches = router.route(&request);
|
let matches = router.route(&request);
|
||||||
if matches.len() > 0 {
|
if matches.len() > 0 {
|
||||||
|
|
|
@ -24,8 +24,9 @@ fn default_rank(path: &str) -> isize {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Route {
|
impl Route {
|
||||||
pub fn ranked<S>(rank: isize, m: Method, path: S, handler: Handler)
|
pub fn ranked<S>(rank: isize, m: Method, path: S, handler: Handler) -> Route
|
||||||
-> Route where S: AsRef<str> {
|
where S: AsRef<str>
|
||||||
|
{
|
||||||
Route {
|
Route {
|
||||||
method: m,
|
method: m,
|
||||||
path: URIBuf::from(path.as_ref()),
|
path: URIBuf::from(path.as_ref()),
|
||||||
|
@ -35,7 +36,9 @@ impl Route {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn new<S>(m: Method, path: S, handler: Handler) -> Route where S: AsRef<str> {
|
pub fn new<S>(m: Method, path: S, handler: Handler) -> Route
|
||||||
|
where S: AsRef<str>
|
||||||
|
{
|
||||||
Route {
|
Route {
|
||||||
method: m,
|
method: m,
|
||||||
handler: handler,
|
handler: handler,
|
||||||
|
@ -45,7 +48,9 @@ impl Route {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn set_path<S>(&mut self, path: S) where S: AsRef<str> {
|
pub fn set_path<S>(&mut self, path: S)
|
||||||
|
where S: AsRef<str>
|
||||||
|
{
|
||||||
self.path = URIBuf::from(path.as_ref());
|
self.path = URIBuf::from(path.as_ref());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -58,9 +63,11 @@ impl Route {
|
||||||
|
|
||||||
let mut result = Vec::with_capacity(self.path.segment_count());
|
let mut result = Vec::with_capacity(self.path.segment_count());
|
||||||
for (route_seg, uri_seg) in route_segs.zip(uri_segs) {
|
for (route_seg, uri_seg) in route_segs.zip(uri_segs) {
|
||||||
if route_seg.ends_with("..>") { // FIXME: Here.
|
if route_seg.ends_with("..>") {
|
||||||
|
// FIXME: Here.
|
||||||
break;
|
break;
|
||||||
} else if route_seg.ends_with('>') { // FIXME: Here.
|
} else if route_seg.ends_with('>') {
|
||||||
|
// FIXME: Here.
|
||||||
result.push(uri_seg);
|
result.push(uri_seg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
@ -8,7 +8,7 @@ pub struct URI<'a> {
|
||||||
uri: &'a str,
|
uri: &'a str,
|
||||||
path: &'a str,
|
path: &'a str,
|
||||||
query: Option<&'a str>,
|
query: Option<&'a str>,
|
||||||
segment_count: Cell<Option<usize>>
|
segment_count: Cell<Option<usize>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> URI<'a> {
|
impl<'a> URI<'a> {
|
||||||
|
@ -17,7 +17,7 @@ impl<'a> URI<'a> {
|
||||||
|
|
||||||
let (path, query) = match uri.find('?') {
|
let (path, query) = match uri.find('?') {
|
||||||
Some(index) => (&uri[..index], Some(&uri[(index + 1)..])),
|
Some(index) => (&uri[..index], Some(&uri[(index + 1)..])),
|
||||||
None => (uri, None)
|
None => (uri, None),
|
||||||
};
|
};
|
||||||
|
|
||||||
URI {
|
URI {
|
||||||
|
@ -53,7 +53,10 @@ impl<'a> fmt::Display for URI<'a> {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||||
let mut last = '\0';
|
let mut last = '\0';
|
||||||
for c in self.uri.chars() {
|
for c in self.uri.chars() {
|
||||||
if !(c == '/' && last == '/') { f.write_char(c)?; }
|
if !(c == '/' && last == '/') {
|
||||||
|
f.write_char(c)?;
|
||||||
|
}
|
||||||
|
|
||||||
last = c;
|
last = c;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -66,7 +69,7 @@ unsafe impl<'a> Sync for URI<'a> { /* It's safe! */ }
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct URIBuf {
|
pub struct URIBuf {
|
||||||
uri: String,
|
uri: String,
|
||||||
segment_count: Cell<Option<usize>>
|
segment_count: Cell<Option<usize>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
// I don't like repeating all of this stuff. Is there a better way?
|
// I don't like repeating all of this stuff. Is there a better way?
|
||||||
|
@ -160,7 +163,7 @@ impl<'a> Iterator for Segments<'a> {
|
||||||
// Find the start of the next segment (first that's not '/').
|
// Find the start of the next segment (first that's not '/').
|
||||||
let i = match self.0.find(|c| c != '/') {
|
let i = match self.0.find(|c| c != '/') {
|
||||||
Some(index) => index,
|
Some(index) => index,
|
||||||
None => return None
|
None => return None,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Get the index of the first character that _is_ a '/' after start.
|
// Get the index of the first character that _is_ a '/' after start.
|
||||||
|
|
|
@ -1,3 +1,2 @@
|
||||||
enum_trailing_comma = false
|
|
||||||
max_width = 85
|
max_width = 85
|
||||||
fn_call_width = 80
|
fn_call_width = 80
|
||||||
|
|
Loading…
Reference in New Issue