Namespace HTTP-related type under `http`.

This commit is contained in:
Sergio Benitez 2016-10-03 17:09:13 -07:00
parent 17b88d0a6b
commit 74ec26db95
34 changed files with 170 additions and 121 deletions

View File

@ -14,29 +14,29 @@ use syntax::ext::build::AstBuilder;
use syntax::parse::token::{self, str_to_ident};
use syntax::ptr::P;
use rocket::{Method, ContentType};
use rocket::content_type::{TopLevel, SubLevel};
use rocket::http::{Method, ContentType};
use rocket::http::mime::{TopLevel, SubLevel};
fn method_to_path(ecx: &ExtCtxt, method: Method) -> Path {
quote_enum!(ecx, method => ::rocket::Method {
quote_enum!(ecx, method => ::rocket::http::Method {
Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch;
})
}
// FIXME: This should return an Expr! (Ext is not a path.)
fn top_level_to_expr(ecx: &ExtCtxt, level: &TopLevel) -> Path {
quote_enum!(ecx, *level => ::rocket::content_type::TopLevel {
quote_enum!(ecx, *level => ::rocket::http::mime::TopLevel {
Star, Text, Image, Audio, Video, Application, Multipart, Model, Message;
Ext(ref s) => quote_path!(ecx, ::rocket::content_type::TopLevel::Ext($s))
Ext(ref s) => quote_path!(ecx, ::rocket::http::mime::TopLevel::Ext($s))
})
}
// FIXME: This should return an Expr! (Ext is not a path.)
fn sub_level_to_expr(ecx: &ExtCtxt, level: &SubLevel) -> Path {
quote_enum!(ecx, *level => ::rocket::content_type::SubLevel {
quote_enum!(ecx, *level => ::rocket::http::mime::SubLevel {
Star, Plain, Html, Xml, Javascript, Css, EventStream, Json,
WwwFormUrlEncoded, Msgpack, OctetStream, FormData, Png, Gif, Bmp, Jpeg;
Ext(ref s) => quote_path!(ecx, ::rocket::content_type::SubLevel::Ext($s))
Ext(ref s) => quote_path!(ecx, ::rocket::http::mime::SubLevel::Ext($s))
})
}
@ -44,7 +44,7 @@ fn content_type_to_expr(ecx: &ExtCtxt, ct: Option<ContentType>) -> Option<P<Expr
ct.map(|ct| {
let top_level = top_level_to_expr(ecx, &ct.0);
let sub_level = sub_level_to_expr(ecx, &ct.1);
quote_expr!(ecx, ::rocket::ContentType($top_level, $sub_level, None))
quote_expr!(ecx, ::rocket::http::ContentType($top_level, $sub_level, None))
})
}

View File

@ -9,7 +9,7 @@ use syntax::parse::token::str_to_ident;
use utils::{span, MetaItemExt, SpanExt};
use super::{Function, ParamIter};
use super::keyvalue::KVSpanned;
use rocket::{Method, ContentType};
use rocket::http::{Method, ContentType};
/// This structure represents the parsed `route` attribute.
///
@ -123,7 +123,7 @@ impl RouteParams {
}
fn is_valid_method(method: Method) -> bool {
use rocket::Method::*;
use rocket::http::Method::*;
match method {
Get | Put | Post | Delete | Patch => true,
_ => false

View File

@ -4,8 +4,8 @@ extern crate serde_json;
use std::ops::{Deref, DerefMut};
use rocket::request::{Request, FromRequest};
use rocket::response::{Responder, Outcome, FreshHyperResponse};
use rocket::response::data;
use rocket::response::{Responder, Outcome, data};
use rocket::http::hyper::FreshHyperResponse;
use self::serde::{Serialize, Deserialize};
use self::serde_json::Error as JSONError;

View File

@ -10,13 +10,16 @@ mod handlebars_templates;
#[macro_use] mod macros;
use self::serde::Serialize;
use self::glob::glob;
use std::path::{Path, PathBuf};
use std::collections::HashMap;
use self::serde::Serialize;
use rocket::response::{Content, Outcome, FreshHyperResponse, Responder};
use rocket::{Rocket, ContentType};
use self::glob::glob;
use rocket::Rocket;
use rocket::response::{Content, Outcome, Responder};
use rocket::http::hyper::FreshHyperResponse;
use rocket::http::ContentType;
/// The Template type implements generic support for template rendering in
/// Rocket.

View File

@ -4,7 +4,8 @@
extern crate rocket;
extern crate serde_json;
use rocket::{Rocket, Request, Error, ContentType};
use rocket::{Rocket, Request, Error};
use rocket::http::ContentType;
use rocket::response::data;
#[derive(Debug, Serialize, Deserialize)]

View File

@ -8,7 +8,7 @@ extern crate tera;
use rocket::Rocket;
use rocket::response::Redirect;
use rocket::request::{Cookie, Cookies};
use rocket::http::{Cookie, Cookies};
lazy_static!(static ref TERA: tera::Tera = tera::Tera::new("templates/**/*"););

View File

@ -1,7 +1,7 @@
extern crate rocket;
use rocket::{Rocket, Request, Response, Route};
use rocket::Method::*;
use rocket::http::Method::*;
fn root<'r>(req: &'r Request<'r>) -> Response<'r> {
let name = req.get_param(0).unwrap_or("unnamed");

View File

@ -15,7 +15,8 @@ fn main() {
#[cfg(test)]
mod test {
use super::rocket::{Rocket, Request, Method};
use super::rocket::{Rocket, Request};
use super::rocket::http::Method;
fn run_test<F>(f: F) where F: Fn(Rocket) {
let mut rocket = Rocket::new("_", 0);

View File

@ -8,5 +8,5 @@ term-painter = "^0.2"
log = "^0.3"
hyper = { version = "^0.9", default-features = false }
url = "^1"
mime = "^0.2"
# mime = "^0.2"
toml = "^0.2"

View File

@ -53,13 +53,16 @@ impl fmt::Display for Catcher {
}
pub mod defaults {
use request::Request;
use response::{StatusCode, Response};
use response::data;
use super::Catcher;
use error::Error;
use std::collections::HashMap;
use request::Request;
use response::Response;
use response::data;
use error::Error;
use http::hyper::StatusCode;
pub fn not_found<'r>(_error: Error, _request: &'r Request<'r>) -> Response<'r> {
Response::with_status(StatusCode::NotFound, data::HTML(r#"
<!DOCTYPE html>

View File

@ -1,5 +1,5 @@
use ::{Method, Handler, ErrorHandler};
use content_type::ContentType;
use handler::{Handler, ErrorHandler};
use http::{Method, ContentType};
pub struct StaticRouteInfo {
pub method: Method,

View File

@ -1,11 +1,10 @@
pub use response::mime::{Mime, TopLevel, SubLevel};
use response::mime::Param;
use std::default::Default;
use std::str::FromStr;
use std::borrow::Borrow;
use std::fmt;
use http::mime::{Mime, Param, TopLevel, SubLevel};
use router::Collider;
/// Typed representation of HTTP Content-Types.
@ -51,8 +50,8 @@ impl ContentType {
/// # Examples
///
/// ```rust
/// use rocket::ContentType;
/// use rocket::response::mime::{TopLevel, SubLevel};
/// use rocket::http::ContentType;
/// use rocket::http::mime::{TopLevel, SubLevel};
///
/// let html = ContentType::of(TopLevel::Application, SubLevel::Html);
/// assert!(html.is_html());
@ -109,7 +108,7 @@ impl ContentType {
/// A recognized content type:
///
/// ```rust
/// use rocket::ContentType;
/// use rocket::http::ContentType;
///
/// let xml = ContentType::from_extension("xml");
/// assert!(xml.is_xml());
@ -118,7 +117,7 @@ impl ContentType {
/// An unrecognized content type:
///
/// ```rust
/// use rocket::ContentType;
/// use rocket::http::ContentType;
///
/// let foo = ContentType::from_extension("foo");
/// assert!(foo.is_any());
@ -203,8 +202,8 @@ impl FromStr for ContentType {
/// Parsing an `application/json`:
///
/// ```rust
/// use rocket::ContentType;
/// use std::str::FromStr;
/// use rocket::http::ContentType;
///
/// let json = ContentType::from_str("application/json");
/// assert_eq!(json, Ok(ContentType::json()));
@ -213,9 +212,9 @@ impl FromStr for ContentType {
/// Parsing a content-type extension:
///
/// ```rust
/// use rocket::ContentType;
/// use std::str::FromStr;
/// use rocket::response::mime::{TopLevel, SubLevel};
/// use rocket::http::ContentType;
/// use rocket::http::mime::{TopLevel, SubLevel};
///
/// let custom = ContentType::from_str("application/x-custom").unwrap();
/// assert!(custom.is_ext());
@ -226,8 +225,8 @@ impl FromStr for ContentType {
/// Parsing an invalid Content-Type value:
///
/// ```rust
/// use rocket::ContentType;
/// use std::str::FromStr;
/// use rocket::http::ContentType;
///
/// let custom = ContentType::from_str("application//x-custom");
/// assert!(custom.is_err());
@ -273,7 +272,7 @@ impl fmt::Display for ContentType {
/// # Example
///
/// ```rust
/// use rocket::ContentType;
/// use rocket::http::ContentType;
///
/// let http_ct = format!("{}", ContentType::xml());
/// assert_eq!(http_ct, "application/xml".to_string());

4
lib/src/http/cookies.rs Normal file
View File

@ -0,0 +1,4 @@
pub use http::hyper::HyperCookiePair as Cookie;
use http;
pub type Cookies = http::hyper::HyperCookieJar<'static>;

22
lib/src/http/hyper.rs Normal file
View File

@ -0,0 +1,22 @@
// TODO: Removed from Rocket in favor of a more flexible HTTP library.
pub use hyper::server::Request as HyperRequest;
pub use hyper::server::Response as HyperResponse;
pub use hyper::server::Server as HyperServer;
pub use hyper::server::Handler as HyperHandler;
pub use hyper::header::Headers as HyperHeaders;
pub use hyper::header::CookiePair as HyperCookiePair;
pub use hyper::header::CookieJar as HyperCookieJar;
pub use hyper::header::Cookie as HyperCookie;
pub use hyper::header::SetCookie as HyperSetCookie;
pub use hyper::method::Method as HyperMethod;
pub use hyper::uri::RequestUri as HyperRequestUri;
pub use hyper::net::Fresh as HyperFresh;
pub use hyper::header;
// This is okay.
pub use hyper::status::StatusCode;
// TODO: Removed from Rocket in favor of a more flexible HTTP library.
pub type FreshHyperResponse<'a> = self::HyperResponse<'a, self::HyperFresh>;

View File

@ -1,9 +1,9 @@
use super::*;
use self::Method::*;
use std::fmt;
use std::str::FromStr;
use hyper::method::Method as HyperMethod;
use error::Error;
use http::hyper::HyperMethod;
use self::Method::*;
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Method {

13
lib/src/http/mod.rs Normal file
View File

@ -0,0 +1,13 @@
pub mod hyper;
mod cookies;
mod method;
mod content_type;
// TODO: Removed from Rocket in favor of a more flexible HTTP library.
pub use hyper::mime;
pub use self::method::Method;
pub use self::hyper::StatusCode;
pub use self::content_type::ContentType;
pub use self::cookies::{Cookie, Cookies};

View File

@ -58,20 +58,20 @@
//!
//! Rocket is configured via the `Rocket.toml` file.
//!
#[macro_use] extern crate log;
extern crate term_painter;
extern crate hyper;
extern crate url;
extern crate mime;
// extern crate mime;
extern crate toml;
#[macro_use] extern crate log;
#[doc(hidden)] #[macro_use] pub mod logger;
#[doc(hidden)] pub mod content_type;
#[doc(hidden)] pub mod http;
pub mod form;
pub mod request;
pub mod response;
mod method;
mod error;
mod router;
mod rocket;
@ -81,7 +81,9 @@ mod config;
/// Defines the types for request and error handlers.
pub mod handler {
use super::{Request, Response, Error};
use request::Request;
use response::Response;
use error::Error;
/// The type of a request handler.
pub type Handler = for<'r> fn(&'r Request<'r>) -> Response<'r>;
@ -93,12 +95,10 @@ pub mod handler {
#[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 codegen::{StaticRouteInfo, StaticCatchInfo};
pub use router::Route;
pub use request::Request;
pub use method::Method;
pub use error::Error;
pub use router::{Router, Route};
pub use catcher::Catcher;
pub use rocket::Rocket;

View File

@ -1,7 +1,7 @@
use request::*;
use method::Method;
use std::fmt::Debug;
use content_type::ContentType;
use request::Request;
use http::{ContentType, Method, Cookies};
pub trait FromRequest<'r, 'c>: Sized {
type Error: Debug;

View File

@ -7,12 +7,3 @@ mod from_request;
pub use self::request::Request;
pub use self::from_request::FromRequest;
pub use self::param::{FromParam, FromSegments};
pub use hyper::header::CookiePair as Cookie;
// Unexported Hyper types.
#[doc(hidden)] pub use hyper::server::Request as HyperRequest;
#[doc(hidden)] pub use hyper::header::Headers as HyperHeaders;
#[doc(hidden)] pub use hyper::header::Cookie as HyperCookie;
use hyper::header::CookieJar;
pub type Cookies = CookieJar<'static>;

View File

@ -7,17 +7,14 @@ use term_painter::ToStyle;
use error::Error;
use super::{FromParam, FromSegments};
use method::Method;
use content_type::ContentType;
use hyper::uri::RequestUri as HyperRequestUri;
use hyper::header;
use router::URIBuf;
use router::URI;
use router::Route;
// Hyper stuff.
use request::{Cookies, HyperCookie, HyperHeaders, HyperRequest};
use http::hyper::{HyperCookie, HyperHeaders, HyperRequest, HyperRequestUri};
use http::{Method, ContentType, Cookies};
/// The type for all incoming web requests.
///

View File

@ -1,6 +1,7 @@
use response::{header, Responder, FreshHyperResponse, Outcome};
use response::mime::{Mime, TopLevel, SubLevel};
use ::ContentType;
use response::{Responder, Outcome};
use http::hyper::{header, FreshHyperResponse};
use http::mime::{Mime, TopLevel, SubLevel};
use http::ContentType;
pub struct Content<T: Responder>(pub ContentType, pub T);

View File

@ -1,6 +1,9 @@
use response::*;
use std::io::Write;
use response::{Outcome, Responder};
use http::hyper::{header, FreshHyperResponse};
use http::hyper::StatusCode;
pub struct Empty(StatusCode);
impl Empty {

View File

@ -1,7 +1,8 @@
use response::*;
use std::convert::AsRef;
use hyper::header::{SetCookie, CookiePair};
use response::{Outcome, Responder};
use request::{Request, FromRequest};
use http::hyper::{HyperSetCookie, HyperCookiePair, FreshHyperResponse};
const FLASH_COOKIE_NAME: &'static str = "_flash";
@ -32,9 +33,9 @@ impl<R: Responder> Flash<R> {
Flash::new(responder, "error", msg)
}
fn cookie_pair(&self) -> CookiePair {
fn cookie_pair(&self) -> HyperCookiePair {
let content = format!("{}{}{}", self.name.len(), self.name, self.message);
let mut pair = CookiePair::new(FLASH_COOKIE_NAME.to_string(), content);
let mut pair = HyperCookiePair::new(FLASH_COOKIE_NAME.to_string(), content);
pair.path = Some("/".to_string());
pair.max_age = Some(300);
pair
@ -44,7 +45,7 @@ impl<R: Responder> Flash<R> {
impl<R: Responder> Responder for Flash<R> {
fn respond<'b>(&mut self, mut res: FreshHyperResponse<'b>) -> Outcome<'b> {
trace_!("Flash: setting message: {}:{}", self.name, self.message);
res.headers_mut().set(SetCookie(vec![self.cookie_pair()]));
res.headers_mut().set(HyperSetCookie(vec![self.cookie_pair()]));
self.responder.respond(res)
}
}

View File

@ -9,11 +9,6 @@ mod stream;
pub mod data;
pub use hyper::net::Fresh as HyperFresh;
pub use hyper::status::StatusCode;
pub use hyper::header;
pub use hyper::mime;
pub use self::responder::Responder;
pub use self::empty::{Empty, Forward};
pub use self::redirect::Redirect;
@ -25,8 +20,7 @@ pub use self::stream::Stream;
pub use self::data::Content;
use std::ops::{Deref, DerefMut};
pub type FreshHyperResponse<'a> = ::hyper::server::Response<'a, HyperFresh>;
use http::hyper::StatusCode;
pub struct Response<'a>(Box<Responder + 'a>);

View File

@ -1,10 +1,12 @@
use response::*;
use content_type::ContentType;
use std::fs::File;
use std::path::{Path, PathBuf};
use std::io;
use std::ops::{Deref, DerefMut};
use response::{Responder, Outcome};
use http::hyper::{header, FreshHyperResponse};
use http::ContentType;
#[derive(Debug)]
pub struct NamedFile(PathBuf, File);

View File

@ -1,8 +1,9 @@
use response::*;
use std::fmt;
use term_painter::Color::*;
use term_painter::ToStyle;
use std::fmt;
use http::hyper::FreshHyperResponse;
pub enum Outcome<'h> {
/// Signifies a response that completed sucessfully.

View File

@ -1,4 +1,5 @@
use response::*;
use response::{Outcome, Responder};
use http::hyper::{header, FreshHyperResponse, StatusCode};
#[derive(Debug)]
pub struct Redirect(StatusCode, String);

View File

@ -1,9 +1,11 @@
use response::*;
use response::mime::{Mime, TopLevel, SubLevel};
use std::io::{Read, Write};
use std::fs::File;
use std::fmt;
use response::Outcome;
use http::mime::{Mime, TopLevel, SubLevel};
use http::hyper::{header, FreshHyperResponse, StatusCode};
// TODO: Have this return something saying whether every was okay. Need
// something like to be able to forward requests on when things don't work out.
// In particular, we want to try the next ranked route when when parsing

View File

@ -1,6 +1,8 @@
use response::*;
use std::io::{Read, Write, ErrorKind};
use response::{Responder, Outcome};
use http::hyper::FreshHyperResponse;
// TODO: Support custom chunk sizes.
/// The default size of each chunk in the streamed response.
pub const CHUNK_SIZE: usize = 4096;

View File

@ -1,4 +1,5 @@
use response::*;
use response::{Responder, Outcome};
use http::hyper::{StatusCode, FreshHyperResponse};
pub struct StatusResponse<R: Responder> {
status: StatusCode,

View File

@ -1,9 +1,3 @@
use super::*;
use response::{FreshHyperResponse, Outcome};
use request::HyperRequest;
use catcher;
use config::RocketConfig;
use std::collections::HashMap;
use std::str::from_utf8_unchecked;
use std::cmp::min;
@ -12,9 +6,18 @@ use std::process;
use term_painter::Color::*;
use term_painter::ToStyle;
use hyper::server::Server as HyperServer;
use hyper::server::Handler as HyperHandler;
use hyper::header::SetCookie;
use logger::{self, LoggingLevel};
use request::Request;
use router::{Router, Route};
use catcher::{self, Catcher};
use response::Outcome;
use config::RocketConfig;
use form::FormItems;
use error::Error;
use http::Method;
use http::hyper::{HyperRequest, FreshHyperResponse};
use http::hyper::{HyperServer, HyperHandler, HyperSetCookie, header};
pub struct Rocket {
address: String,
@ -28,7 +31,7 @@ impl HyperHandler for Rocket {
fn handle<'h, 'k>(&self,
req: HyperRequest<'h, 'k>,
mut res: FreshHyperResponse<'h>) {
res.headers_mut().set(response::header::Server("rocket".to_string()));
res.headers_mut().set(header::Server("rocket".to_string()));
self.dispatch(req, res)
}
}
@ -64,7 +67,7 @@ impl Rocket {
let mut responder = (route.handler)(&request);
let cookie_delta = request.cookies().delta();
if cookie_delta.len() > 0 {
res.headers_mut().set(SetCookie(cookie_delta));
res.headers_mut().set(HyperSetCookie(cookie_delta));
}
// Get the response.
@ -95,7 +98,7 @@ impl Rocket {
from_utf8_unchecked(&req.data.as_slice()[..min(data_len, max_len)])
};
let mut form_items = form::FormItems(form);
let mut form_items = FormItems(form);
if let Some(("_method", value)) = form_items.next() {
if let Ok(method) = value.parse() {
req.method = method;

View File

@ -46,14 +46,15 @@ impl<'a> Collider<str> for &'a str {
#[cfg(test)]
mod tests {
use router::Collider;
use router::route::Route;
use Method;
use Method::*;
use {Request, Response};
use content_type::ContentType;
use std::str::FromStr;
use router::URI;
use router::{Collider, URI};
use request::Request;
use response::Response;
use router::route::Route;
use http::{Method, ContentType};
use http::Method::*;
type SimpleRoute = (Method, &'static str);

View File

@ -7,7 +7,8 @@ pub use self::uri::{URI, URIBuf, Segments};
pub use self::route::Route;
use std::collections::hash_map::HashMap;
use method::Method;
use http::Method;
use request::Request;
// type Selector = (Method, usize);
@ -68,11 +69,11 @@ impl Router {
#[cfg(test)]
mod test {
use method::Method;
use method::Method::*;
use super::{Router, Route};
use super::{Router, Route, URI};
use http::Method;
use http::Method::*;
use {Response, Request};
use super::URI;
fn dummy_handler(_req: &Request) -> Response<'static> {
Response::empty()

View File

@ -1,13 +1,15 @@
use ::{Method, Handler, StaticRouteInfo};
use content_type::ContentType;
use super::{Collider, URI, URIBuf}; // :D
use std::fmt;
use std::convert::From;
use term_painter::ToStyle;
use term_painter::Color::*;
use std::fmt;
use std::convert::From;
use super::{Collider, URI, URIBuf}; // :D
use codegen::StaticRouteInfo;
use handler::Handler;
use request::Request;
use http::{Method, ContentType};
pub struct Route {
pub method: Method,