1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-12-19 14:49:01 +00:00

re-arrange modules and exports

This commit is contained in:
Nikolay Kim 2018-03-30 17:31:18 -07:00
parent b16419348e
commit 9e751de707
49 changed files with 373 additions and 483 deletions

View file

@ -23,7 +23,7 @@ Here is an example of a simple middleware that adds request and response headers
# extern crate http; # extern crate http;
# extern crate actix_web; # extern crate actix_web;
use http::{header, HttpTryFrom}; use http::{header, HttpTryFrom};
use actix_web::*; use actix_web::{Application, HttpRequest, HttpResponse, Result, httpcodes};
use actix_web::middleware::{Middleware, Started, Response}; use actix_web::middleware::{Middleware, Started, Response};
struct Headers; // <- Our middleware struct Headers; // <- Our middleware
@ -135,7 +135,7 @@ the specified header.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::*; use actix_web::{Application, http, httpcodes, middleware};
fn main() { fn main() {
let app = Application::new() let app = Application::new()
@ -144,8 +144,8 @@ fn main() {
.header("X-Version", "0.2") .header("X-Version", "0.2")
.finish()) .finish())
.resource("/test", |r| { .resource("/test", |r| {
r.method(Method::GET).f(|req| httpcodes::HttpOk); r.method(http::Method::GET).f(|req| httpcodes::HttpOk);
r.method(Method::HEAD).f(|req| httpcodes::HttpMethodNotAllowed); r.method(http::Method::HEAD).f(|req| httpcodes::HttpMethodNotAllowed);
}) })
.finish(); .finish();
} }

View file

@ -7,12 +7,12 @@ match path tail we can use `[.*]` regex.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::*;
use std::path::PathBuf; use std::path::PathBuf;
use actix_web::{Application, HttpRequest, Result, http::Method, fs::NamedFile};
fn index(req: HttpRequest) -> Result<fs::NamedFile> { fn index(req: HttpRequest) -> Result<NamedFile> {
let path: PathBuf = req.match_info().query("tail")?; let path: PathBuf = req.match_info().query("tail")?;
Ok(fs::NamedFile::open(path)?) Ok(NamedFile::open(path)?)
} }
fn main() { fn main() {

View file

@ -80,8 +80,8 @@ in the state:
# extern crate actix; # extern crate actix;
# extern crate actix_web; # extern crate actix_web;
# #
use actix_web::*;
use std::cell::Cell; use std::cell::Cell;
use actix_web::{Application, HttpRequest, http};
// This struct represents state // This struct represents state
struct AppState { struct AppState {
@ -97,7 +97,7 @@ fn index(req: HttpRequest<AppState>) -> String {
fn main() { fn main() {
Application::with_state(AppState{counter: Cell::new(0)}) Application::with_state(AppState{counter: Cell::new(0)})
.resource("/", |r| r.method(Method::GET).f(index)) .resource("/", |r| r.method(http::Method::GET).f(index))
.finish(); .finish();
} }
``` ```

View file

@ -172,11 +172,11 @@ and is on for *HTTP/1.1* and *HTTP/2.0*.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{header, HttpRequest, HttpResponse, httpcodes::HttpOk}; use actix_web::{HttpRequest, HttpResponse, http, httpcodes::HttpOk};
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
HttpOk.build() HttpOk.build()
.connection_type(header::ConnectionType::Close) // <- Close connection .connection_type(http::ConnectionType::Close) // <- Close connection
.force_close() // <- Alternative method .force_close() // <- Alternative method
.finish().unwrap() .finish().unwrap()
} }

View file

@ -130,7 +130,7 @@ Let's create a response for a custom type that serializes to an `application/jso
extern crate serde; extern crate serde;
extern crate serde_json; extern crate serde_json;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
use actix_web::*; use actix_web::{Application, HttpServer, HttpRequest, HttpResponse, Error, Responder, http};
#[derive(Serialize)] #[derive(Serialize)]
struct MyObj { struct MyObj {
@ -142,7 +142,7 @@ impl Responder for MyObj {
type Item = HttpResponse; type Item = HttpResponse;
type Error = Error; type Error = Error;
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse> { fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, Error> {
let body = serde_json::to_string(&self)?; let body = serde_json::to_string(&self)?;
// Create response and set content type // Create response and set content type
@ -162,7 +162,7 @@ fn main() {
HttpServer::new( HttpServer::new(
|| Application::new() || Application::new()
.resource("/", |r| r.method(Method::GET).f(index))) .resource("/", |r| r.method(http::Method::GET).f(index)))
.bind("127.0.0.1:8088").unwrap() .bind("127.0.0.1:8088").unwrap()
.start(); .start();

View file

@ -70,7 +70,7 @@ to return different responses for different types of errors.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
#[macro_use] extern crate failure; #[macro_use] extern crate failure;
use actix_web::*; use actix_web::{Application, Body, HttpRequest, HttpResponse, http, error};
#[derive(Fail, Debug)] #[derive(Fail, Debug)]
enum MyError { enum MyError {
@ -86,11 +86,11 @@ impl error::ResponseError for MyError {
fn error_response(&self) -> HttpResponse { fn error_response(&self) -> HttpResponse {
match *self { match *self {
MyError::InternalError => HttpResponse::new( MyError::InternalError => HttpResponse::new(
StatusCode::INTERNAL_SERVER_ERROR, Body::Empty), http::StatusCode::INTERNAL_SERVER_ERROR, Body::Empty),
MyError::BadClientData => HttpResponse::new( MyError::BadClientData => HttpResponse::new(
StatusCode::BAD_REQUEST, Body::Empty), http::StatusCode::BAD_REQUEST, Body::Empty),
MyError::Timeout => HttpResponse::new( MyError::Timeout => HttpResponse::new(
StatusCode::GATEWAY_TIMEOUT, Body::Empty), http::StatusCode::GATEWAY_TIMEOUT, Body::Empty),
} }
} }
} }

View file

@ -21,8 +21,8 @@ and a resource configuration function.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# use actix_web::*; # use actix_web::{Application, HttpRequest, HttpResponse, http::Method};
# use actix_web::httpcodes::*; # use actix_web::httpcodes::HttpOk;
# #
# fn index(req: HttpRequest) -> HttpResponse { # fn index(req: HttpRequest) -> HttpResponse {
# unimplemented!() # unimplemented!()
@ -305,8 +305,8 @@ safe to interpolate within, or use as a suffix of, a path without additional che
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::*;
use std::path::PathBuf; use std::path::PathBuf;
use actix_web::{Application, HttpRequest, Result, http::Method};
fn index(req: HttpRequest) -> Result<String> { fn index(req: HttpRequest) -> Result<String> {
let path: PathBuf = req.match_info().query("tail")?; let path: PathBuf = req.match_info().query("tail")?;
@ -335,7 +335,7 @@ has to implement *serde's *`Deserialize` trait.
# extern crate actix_web; # extern crate actix_web;
# extern crate futures; # extern crate futures;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
use actix_web::*; use actix_web::{Application, Path, Result, http::Method};
#[derive(Deserialize)] #[derive(Deserialize)]
struct Info { struct Info {
@ -366,8 +366,8 @@ resource with the name "foo" and the pattern "{a}/{b}/{c}", you might do this:
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# use actix_web::*; # use actix_web::{Application, HttpRequest, HttpResponse, http::Method};
# use actix_web::httpcodes::*; # use actix_web::httpcodes::HttpOk;
# #
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
@ -378,7 +378,7 @@ fn main() {
let app = Application::new() let app = Application::new()
.resource("/test/{a}/{b}/{c}", |r| { .resource("/test/{a}/{b}/{c}", |r| {
r.name("foo"); // <- set resource name, then it could be used in `url_for` r.name("foo"); // <- set resource name, then it could be used in `url_for`
r.method(Method::GET).f(|_| httpcodes::HttpOk); r.method(Method::GET).f(|_| HttpOk);
}) })
.finish(); .finish();
} }
@ -437,7 +437,7 @@ This handler designed to be use as a handler for application's *default resource
# extern crate actix_web; # extern crate actix_web;
# #[macro_use] extern crate serde_derive; # #[macro_use] extern crate serde_derive;
# use actix_web::*; # use actix_web::*;
use actix_web::helpers::NormalizePath; use actix_web::http::NormalizePath;
# #
# fn index(req: HttpRequest) -> httpcodes::StaticResponse { # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
# httpcodes::HttpOk # httpcodes::HttpOk
@ -462,8 +462,7 @@ It is possible to register path normalization only for *GET* requests only:
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# #[macro_use] extern crate serde_derive; # #[macro_use] extern crate serde_derive;
# use actix_web::*; use actix_web::{Application, HttpRequest, http::Method, http::NormalizePath, httpcodes};
use actix_web::helpers::NormalizePath;
# #
# fn index(req: HttpRequest) -> httpcodes::StaticResponse { # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
# httpcodes::HttpOk # httpcodes::HttpOk
@ -597,9 +596,8 @@ with `Application::resource()` method.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
# extern crate http; use actix_web::{Application, http::Method, pred};
use actix_web::*; use actix_web::httpcodes::{HttpNotFound, HttpMethodNotAllowed};
use actix_web::httpcodes::*;
fn main() { fn main() {
Application::new() Application::new()

View file

@ -12,7 +12,7 @@ builder instance multiple times, the builder will panic.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{HttpRequest, HttpResponse, header::ContentEncoding}; use actix_web::{HttpRequest, HttpResponse, http::ContentEncoding};
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
@ -45,7 +45,7 @@ to enable `brotli` use `ContentEncoding::Br`:
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
use actix_web::{HttpRequest, HttpResponse, header::ContentEncoding}; use actix_web::{HttpRequest, HttpResponse, http::ContentEncoding};
fn index(req: HttpRequest) -> HttpResponse { fn index(req: HttpRequest) -> HttpResponse {
HttpResponse::Ok() HttpResponse::Ok()
@ -135,7 +135,7 @@ type `T` must implement the `Serialize` trait from *serde*.
```rust ```rust
# extern crate actix_web; # extern crate actix_web;
#[macro_use] extern crate serde_derive; #[macro_use] extern crate serde_derive;
use actix_web::*; use actix_web::{Application, HttpRequest, Json, Result, http::Method};
#[derive(Serialize)] #[derive(Serialize)]
struct MyObj { struct MyObj {

View file

@ -178,14 +178,14 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::*; /// use actix_web::{Application, http, httpcodes};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = Application::new()
/// .prefix("/app") /// .prefix("/app")
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HttpOk); /// r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed); /// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// }) /// })
/// .finish(); /// .finish();
/// } /// }
@ -222,13 +222,13 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::*; /// use actix_web::{Application, http, httpcodes};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = Application::new()
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HttpOk); /// r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed); /// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// }); /// });
/// } /// }
/// ``` /// ```
@ -277,7 +277,7 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::*; /// use actix_web::{Application, HttpRequest, HttpResponse, Result, httpcodes};
/// ///
/// fn index(mut req: HttpRequest) -> Result<HttpResponse> { /// fn index(mut req: HttpRequest) -> Result<HttpResponse> {
/// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?; /// let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
@ -315,14 +315,14 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::*; /// use actix_web::{Application, HttpRequest, http, httpcodes};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = Application::new()
/// .handler("/app", |req: HttpRequest| { /// .handler("/app", |req: HttpRequest| {
/// match *req.method() { /// match *req.method() {
/// Method::GET => httpcodes::HttpOk, /// http::Method::GET => httpcodes::HttpOk,
/// Method::POST => httpcodes::HttpMethodNotAllowed, /// http::Method::POST => httpcodes::HttpMethodNotAllowed,
/// _ => httpcodes::HttpNotFound, /// _ => httpcodes::HttpNotFound,
/// }}); /// }});
/// } /// }
@ -352,14 +352,14 @@ impl<S> Application<S> where S: 'static {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::*; /// use actix_web::{Application, http, httpcodes, fs, middleware};
/// ///
/// // this function could be located in different module /// // this function could be located in different module
/// fn config(app: Application) -> Application { /// fn config(app: Application) -> Application {
/// app /// app
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HttpOk); /// r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed); /// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// }) /// })
/// } /// }
/// ///

View file

@ -312,16 +312,14 @@ impl ClientRequestBuilder {
/// ```rust /// ```rust
/// # extern crate mime; /// # extern crate mime;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*;
/// # use actix_web::httpcodes::*;
/// # use actix_web::client::*; /// # use actix_web::client::*;
/// # /// #
/// use actix_web::header; /// use actix_web::{client, http};
/// ///
/// fn main() { /// fn main() {
/// let req = ClientRequest::build() /// let req = client::ClientRequest::build()
/// .set(header::Date::now()) /// .set(http::header::Date::now())
/// .set(header::ContentType(mime::TEXT_HTML)) /// .set(http::header::ContentType(mime::TEXT_HTML))
/// .finish().unwrap(); /// .finish().unwrap();
/// } /// }
/// ``` /// ```
@ -446,16 +444,12 @@ impl ClientRequestBuilder {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// use actix_web::{client, http};
/// # use actix_web::httpcodes::*;
/// #
/// use actix_web::header::Cookie;
/// use actix_web::client::ClientRequest;
/// ///
/// fn main() { /// fn main() {
/// let req = ClientRequest::build() /// let req = client::ClientRequest::build()
/// .cookie( /// .cookie(
/// Cookie::build("name", "value") /// http::Cookie::build("name", "value")
/// .domain("www.rust-lang.org") /// .domain("www.rust-lang.org")
/// .path("/") /// .path("/")
/// .secure(true) /// .secure(true)

View file

@ -19,8 +19,7 @@ use httprequest::HttpRequest;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// # use actix_web::*; /// use actix_web::{Application, Path, Result, http};
/// use actix_web::Path;
/// ///
/// /// extract path info from "/{username}/{count}/?index.html" url /// /// extract path info from "/{username}/{count}/?index.html" url
/// /// {username} - deserializes to a String /// /// {username} - deserializes to a String
@ -32,7 +31,7 @@ use httprequest::HttpRequest;
/// fn main() { /// fn main() {
/// let app = Application::new().resource( /// let app = Application::new().resource(
/// "/{username}/{count}/?index.html", // <- define path parameters /// "/{username}/{count}/?index.html", // <- define path parameters
/// |r| r.method(Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
/// } /// }
/// ``` /// ```
/// ///
@ -44,8 +43,7 @@ use httprequest::HttpRequest;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// # use actix_web::*; /// use actix_web::{Application, Path, Result, http};
/// use actix_web::Path;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -60,7 +58,7 @@ use httprequest::HttpRequest;
/// fn main() { /// fn main() {
/// let app = Application::new().resource( /// let app = Application::new().resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub struct Path<T>{ pub struct Path<T>{
@ -111,8 +109,7 @@ impl<T, S> FromRequest<S> for Path<T>
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// # use actix_web::*; /// use actix_web::{Application, Query, http};
/// use actix_web::Query;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -121,14 +118,14 @@ impl<T, S> FromRequest<S> for Path<T>
/// ///
/// // use `with` extractor for query info /// // use `with` extractor for query info
/// // this handler get called only if request's query contains `username` field /// // this handler get called only if request's query contains `username` field
/// fn index(info: Query<Info>) -> Result<String> { /// fn index(info: Query<Info>) -> String {
/// Ok(format!("Welcome {}!", info.username)) /// format!("Welcome {}!", info.username)
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new().resource( /// let app = Application::new().resource(
/// "/index.html", /// "/index.html",
/// |r| r.method(Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub struct Query<T>(T); pub struct Query<T>(T);

View file

@ -178,8 +178,8 @@ impl Responder for NamedFile {
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> { fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
if self.only_get && *req.method() != Method::GET && *req.method() != Method::HEAD { if self.only_get && *req.method() != Method::GET && *req.method() != Method::HEAD {
return Ok(HttpMethodNotAllowed.build() return Ok(HttpMethodNotAllowed.build()
.header(header::http::CONTENT_TYPE, "text/plain") .header(header::CONTENT_TYPE, "text/plain")
.header(header::http::ALLOW, "GET, HEAD") .header(header::ALLOW, "GET, HEAD")
.body("This resource only supports GET and HEAD.").unwrap()) .body("This resource only supports GET and HEAD.").unwrap())
} }
@ -466,7 +466,7 @@ impl<S: 'static> Handler<S> for StaticFiles<S> {
} }
new_path.push_str(redir_index); new_path.push_str(redir_index);
HttpFound.build() HttpFound.build()
.header(header::http::LOCATION, new_path.as_str()) .header(header::LOCATION, new_path.as_str())
.finish().unwrap() .finish().unwrap()
.respond_to(req.without_state()) .respond_to(req.without_state())
} else if self.show_index { } else if self.show_index {

View file

@ -373,7 +373,6 @@ impl<S, H, F, R, E> RouteHandler<S> for AsyncHandler<S, H, F, R, E>
} }
} }
/// Access to an application state /// Access to an application state
/// ///
/// `S` - application state type /// `S` - application state type
@ -384,9 +383,8 @@ impl<S, H, F, R, E> RouteHandler<S> for AsyncHandler<S, H, F, R, E>
/// # extern crate bytes; /// # extern crate bytes;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// # use actix_web::*;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::State; /// use actix_web::{Application, Path, State, http};
/// ///
/// /// Application state /// /// Application state
/// struct App {msg: &'static str} /// struct App {msg: &'static str}
@ -397,14 +395,14 @@ impl<S, H, F, R, E> RouteHandler<S> for AsyncHandler<S, H, F, R, E>
/// } /// }
/// ///
/// /// extract path info using serde /// /// extract path info using serde
/// fn index(state: State<App>, info: Path<Info>) -> Result<String> { /// fn index(state: State<App>, info: Path<Info>) -> String {
/// Ok(format!("{} {}!", state.msg, info.username)) /// format!("{} {}!", state.msg, info.username)
/// } /// }
/// ///
/// fn main() { /// fn main() {
/// let app = Application::with_state(App{msg: "Welcome"}).resource( /// let app = Application::with_state(App{msg: "Welcome"}).resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(Method::GET).with2(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with2(index)); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub struct State<S> (HttpRequest<S>); pub struct State<S> (HttpRequest<S>);

View file

@ -1,5 +1,6 @@
use mime::{self, Mime}; use mime::{self, Mime};
use header::{QualityItem, qitem, http}; use header::{QualityItem, qitem};
use http::header as http;
header! { header! {
/// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2) /// `Accept` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-5.3.2)
@ -32,7 +33,7 @@ header! {
/// # extern crate actix_web; /// # extern crate actix_web;
/// extern crate mime; /// extern crate mime;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{Accept, qitem}; /// use actix_web::http::header::{Accept, qitem};
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -49,7 +50,7 @@ header! {
/// # extern crate actix_web; /// # extern crate actix_web;
/// extern crate mime; /// extern crate mime;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{Accept, qitem}; /// use actix_web::http::header::{Accept, qitem};
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -66,7 +67,7 @@ header! {
/// # extern crate actix_web; /// # extern crate actix_web;
/// extern crate mime; /// extern crate mime;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{Accept, QualityItem, q, qitem}; /// use actix_web::http::header::{Accept, QualityItem, q, qitem};
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -128,7 +129,7 @@ header! {
#[test] #[test]
fn test_fuzzing1() { fn test_fuzzing1() {
use test::TestRequest; use test::TestRequest;
let req = TestRequest::with_header(http::ACCEPT, "chunk#;e").finish(); let req = TestRequest::with_header(super::http::ACCEPT, "chunk#;e").finish();
let header = Accept::parse(&req); let header = Accept::parse(&req);
assert!(header.is_ok()); assert!(header.is_ok());
} }

View file

@ -1,4 +1,4 @@
use header::{http, Charset, QualityItem}; use header::{ACCEPT_CHARSET, Charset, QualityItem};
header! { header! {
/// `Accept-Charset` header, defined in /// `Accept-Charset` header, defined in
@ -24,7 +24,7 @@ header! {
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{AcceptCharset, Charset, qitem}; /// use actix_web::http::header::{AcceptCharset, Charset, qitem};
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -36,7 +36,7 @@ header! {
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{AcceptCharset, Charset, q, QualityItem}; /// use actix_web::http::header::{AcceptCharset, Charset, q, QualityItem};
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -51,7 +51,7 @@ header! {
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{AcceptCharset, Charset, qitem}; /// use actix_web::http::header::{AcceptCharset, Charset, qitem};
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -60,7 +60,7 @@ header! {
/// ); /// );
/// # } /// # }
/// ``` /// ```
(AcceptCharset, http::ACCEPT_CHARSET) => (QualityItem<Charset>)+ (AcceptCharset, ACCEPT_CHARSET) => (QualityItem<Charset>)+
test_accept_charset { test_accept_charset {
/// Test case from RFC /// Test case from RFC

View file

@ -1,5 +1,5 @@
use language_tags::LanguageTag; use language_tags::LanguageTag;
use header::{http, QualityItem}; use header::{ACCEPT_LANGUAGE, QualityItem};
header! { header! {
@ -27,7 +27,7 @@ header! {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate language_tags; /// # extern crate language_tags;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{AcceptLanguage, LanguageTag, qitem}; /// use actix_web::http::header::{AcceptLanguage, LanguageTag, qitem};
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -46,7 +46,7 @@ header! {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # #[macro_use] extern crate language_tags; /// # #[macro_use] extern crate language_tags;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{AcceptLanguage, QualityItem, q, qitem}; /// use actix_web::http::header::{AcceptLanguage, QualityItem, q, qitem};
/// # /// #
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -59,7 +59,7 @@ header! {
/// ); /// );
/// # } /// # }
/// ``` /// ```
(AcceptLanguage, http::ACCEPT_LANGUAGE) => (QualityItem<LanguageTag>)+ (AcceptLanguage, ACCEPT_LANGUAGE) => (QualityItem<LanguageTag>)+
test_accept_language { test_accept_language {
// From the RFC // From the RFC

View file

@ -1,5 +1,5 @@
use http::Method; use http::Method;
use header::http; use http::header;
header! { header! {
/// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1) /// `Allow` header, defined in [RFC7231](http://tools.ietf.org/html/rfc7231#section-7.4.1)
@ -26,7 +26,7 @@ header! {
/// # extern crate http; /// # extern crate http;
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::Allow; /// use actix_web::http::header::Allow;
/// use http::Method; /// use http::Method;
/// ///
/// # fn main() { /// # fn main() {
@ -41,7 +41,7 @@ header! {
/// # extern crate http; /// # extern crate http;
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::Allow; /// use actix_web::http::header::Allow;
/// use http::Method; /// use http::Method;
/// ///
/// # fn main() { /// # fn main() {
@ -55,7 +55,7 @@ header! {
/// ); /// );
/// # } /// # }
/// ``` /// ```
(Allow, http::ALLOW) => (Method)* (Allow, header::ALLOW) => (Method)*
test_allow { test_allow {
// From the RFC // From the RFC

View file

@ -1,7 +1,8 @@
use std::fmt::{self, Write}; use std::fmt::{self, Write};
use std::str::FromStr; use std::str::FromStr;
use http::header;
use header::{Header, IntoHeaderValue, Writer}; use header::{Header, IntoHeaderValue, Writer};
use header::{http, from_comma_delimited, fmt_comma_delimited}; use header::{from_comma_delimited, fmt_comma_delimited};
/// `Cache-Control` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.2) /// `Cache-Control` header, defined in [RFC7234](https://tools.ietf.org/html/rfc7234#section-5.2)
/// ///
@ -26,7 +27,7 @@ use header::{http, from_comma_delimited, fmt_comma_delimited};
/// # Examples /// # Examples
/// ```rust /// ```rust
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{CacheControl, CacheDirective}; /// use actix_web::http::header::{CacheControl, CacheDirective};
/// ///
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
/// builder.set( /// builder.set(
@ -36,7 +37,7 @@ use header::{http, from_comma_delimited, fmt_comma_delimited};
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::{CacheControl, CacheDirective}; /// use actix_web::http::header::{CacheControl, CacheDirective};
/// ///
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
/// builder.set( /// builder.set(
@ -56,8 +57,8 @@ __hyper__deref!(CacheControl => Vec<CacheDirective>);
//TODO: this could just be the header! macro //TODO: this could just be the header! macro
impl Header for CacheControl { impl Header for CacheControl {
fn name() -> http::HeaderName { fn name() -> header::HeaderName {
http::CACHE_CONTROL header::CACHE_CONTROL
} }
#[inline] #[inline]
@ -80,12 +81,12 @@ impl fmt::Display for CacheControl {
} }
impl IntoHeaderValue for CacheControl { impl IntoHeaderValue for CacheControl {
type Error = http::InvalidHeaderValueBytes; type Error = header::InvalidHeaderValueBytes;
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<header::HeaderValue, Self::Error> {
let mut writer = Writer::new(); let mut writer = Writer::new();
let _ = write!(&mut writer, "{}", self); let _ = write!(&mut writer, "{}", self);
http::HeaderValue::from_shared(writer.take()) header::HeaderValue::from_shared(writer.take())
} }
} }
@ -189,7 +190,7 @@ mod tests {
#[test] #[test]
fn test_parse_multiple_headers() { fn test_parse_multiple_headers() {
let req = TestRequest::with_header( let req = TestRequest::with_header(
http::CACHE_CONTROL, "no-cache, private").finish(); header::CACHE_CONTROL, "no-cache, private").finish();
let cache = Header::parse(&req); let cache = Header::parse(&req);
assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::NoCache, assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::NoCache,
CacheDirective::Private]))) CacheDirective::Private])))
@ -198,7 +199,7 @@ mod tests {
#[test] #[test]
fn test_parse_argument() { fn test_parse_argument() {
let req = TestRequest::with_header( let req = TestRequest::with_header(
http::CACHE_CONTROL, "max-age=100, private").finish(); header::CACHE_CONTROL, "max-age=100, private").finish();
let cache = Header::parse(&req); let cache = Header::parse(&req);
assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::MaxAge(100), assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::MaxAge(100),
CacheDirective::Private]))) CacheDirective::Private])))
@ -207,7 +208,7 @@ mod tests {
#[test] #[test]
fn test_parse_quote_form() { fn test_parse_quote_form() {
let req = TestRequest::with_header( let req = TestRequest::with_header(
http::CACHE_CONTROL, "max-age=\"200\"").finish(); header::CACHE_CONTROL, "max-age=\"200\"").finish();
let cache = Header::parse(&req); let cache = Header::parse(&req);
assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::MaxAge(200)]))) assert_eq!(cache.ok(), Some(CacheControl(vec![CacheDirective::MaxAge(200)])))
} }
@ -215,7 +216,7 @@ mod tests {
#[test] #[test]
fn test_parse_extension() { fn test_parse_extension() {
let req = TestRequest::with_header( let req = TestRequest::with_header(
http::CACHE_CONTROL, "foo, bar=baz").finish(); header::CACHE_CONTROL, "foo, bar=baz").finish();
let cache = Header::parse(&req); let cache = Header::parse(&req);
assert_eq!(cache.ok(), Some(CacheControl(vec![ assert_eq!(cache.ok(), Some(CacheControl(vec![
CacheDirective::Extension("foo".to_owned(), None), CacheDirective::Extension("foo".to_owned(), None),
@ -224,7 +225,7 @@ mod tests {
#[test] #[test]
fn test_parse_bad_syntax() { fn test_parse_bad_syntax() {
let req = TestRequest::with_header(http::CACHE_CONTROL, "foo=").finish(); let req = TestRequest::with_header(header::CACHE_CONTROL, "foo=").finish();
let cache: Result<CacheControl, _> = Header::parse(&req); let cache: Result<CacheControl, _> = Header::parse(&req);
assert_eq!(cache.ok(), None) assert_eq!(cache.ok(), None)
} }

View file

@ -1,5 +1,5 @@
use language_tags::LanguageTag; use language_tags::LanguageTag;
use header::{http, QualityItem}; use header::{CONTENT_LANGUAGE, QualityItem};
header! { header! {
@ -28,7 +28,7 @@ header! {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # #[macro_use] extern crate language_tags; /// # #[macro_use] extern crate language_tags;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// # use actix_web::header::{ContentLanguage, qitem}; /// # use actix_web::http::header::{ContentLanguage, qitem};
/// # /// #
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -44,7 +44,7 @@ header! {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # #[macro_use] extern crate language_tags; /// # #[macro_use] extern crate language_tags;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// # use actix_web::header::{ContentLanguage, qitem}; /// # use actix_web::http::header::{ContentLanguage, qitem};
/// # /// #
/// # fn main() { /// # fn main() {
/// ///
@ -57,7 +57,7 @@ header! {
/// ); /// );
/// # } /// # }
/// ``` /// ```
(ContentLanguage, http::CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+ (ContentLanguage, CONTENT_LANGUAGE) => (QualityItem<LanguageTag>)+
test_content_language { test_content_language {
test_header!(test1, vec![b"da"]); test_header!(test1, vec![b"da"]);

View file

@ -1,13 +1,14 @@
use std::fmt::{self, Display, Write}; use std::fmt::{self, Display, Write};
use std::str::FromStr; use std::str::FromStr;
use header::{http, IntoHeaderValue, Writer};
use error::ParseError; use error::ParseError;
use header::{IntoHeaderValue, Writer,
HeaderValue, InvalidHeaderValueBytes, CONTENT_RANGE};
header! { header! {
/// `Content-Range` header, defined in /// `Content-Range` header, defined in
/// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2) /// [RFC7233](http://tools.ietf.org/html/rfc7233#section-4.2)
(ContentRange, http::CONTENT_RANGE) => [ContentRangeSpec] (ContentRange, CONTENT_RANGE) => [ContentRangeSpec]
test_content_range { test_content_range {
test_header!(test_bytes, test_header!(test_bytes,
@ -195,11 +196,11 @@ impl Display for ContentRangeSpec {
} }
impl IntoHeaderValue for ContentRangeSpec { impl IntoHeaderValue for ContentRangeSpec {
type Error = http::InvalidHeaderValueBytes; type Error = InvalidHeaderValueBytes;
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
let mut writer = Writer::new(); let mut writer = Writer::new();
let _ = write!(&mut writer, "{}", self); let _ = write!(&mut writer, "{}", self);
http::HeaderValue::from_shared(writer.take()) HeaderValue::from_shared(writer.take())
} }
} }

View file

@ -1,5 +1,5 @@
use mime::{self, Mime}; use mime::{self, Mime};
use header::http; use header::CONTENT_TYPE;
header! { header! {
@ -33,7 +33,7 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::ContentType; /// use actix_web::http::header::ContentType;
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -48,7 +48,7 @@ header! {
/// # extern crate actix_web; /// # extern crate actix_web;
/// use mime::TEXT_HTML; /// use mime::TEXT_HTML;
/// use actix_web::httpcodes::HttpOk; /// use actix_web::httpcodes::HttpOk;
/// use actix_web::header::ContentType; /// use actix_web::http::header::ContentType;
/// ///
/// # fn main() { /// # fn main() {
/// let mut builder = HttpOk.build(); /// let mut builder = HttpOk.build();
@ -57,7 +57,7 @@ header! {
/// ); /// );
/// # } /// # }
/// ``` /// ```
(ContentType, http::CONTENT_TYPE) => [Mime] (ContentType, CONTENT_TYPE) => [Mime]
test_content_type { test_content_type {
test_header!( test_header!(

View file

@ -1,5 +1,5 @@
use std::time::SystemTime; use std::time::SystemTime;
use header::{http, HttpDate}; use header::{DATE, HttpDate};
header! { header! {
@ -22,13 +22,13 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::Date; /// use actix_web::http::header::Date;
/// use std::time::SystemTime; /// use std::time::SystemTime;
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// builder.set(Date(SystemTime::now().into())); /// builder.set(Date(SystemTime::now().into()));
/// ``` /// ```
(Date, http::DATE) => [HttpDate] (Date, DATE) => [HttpDate]
test_date { test_date {
test_header!(test1, vec![b"Tue, 15 Nov 1994 08:12:31 GMT"]); test_header!(test1, vec![b"Tue, 15 Nov 1994 08:12:31 GMT"]);

View file

@ -1,4 +1,4 @@
use header::{http, EntityTag}; use header::{ETAG, EntityTag};
header! { header! {
/// `ETag` header, defined in [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.3) /// `ETag` header, defined in [RFC7232](http://tools.ietf.org/html/rfc7232#section-2.3)
@ -29,7 +29,7 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::{ETag, EntityTag}; /// use actix_web::http::header::{ETag, EntityTag};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// builder.set(ETag(EntityTag::new(false, "xyzzy".to_owned()))); /// builder.set(ETag(EntityTag::new(false, "xyzzy".to_owned())));
@ -37,12 +37,12 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::{ETag, EntityTag}; /// use actix_web::http::header::{ETag, EntityTag};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// builder.set(ETag(EntityTag::new(true, "xyzzy".to_owned()))); /// builder.set(ETag(EntityTag::new(true, "xyzzy".to_owned())));
/// ``` /// ```
(ETag, http::ETAG) => [EntityTag] (ETag, ETAG) => [EntityTag]
test_etag { test_etag {
// From the RFC // From the RFC

View file

@ -1,4 +1,4 @@
use header::{http, HttpDate}; use header::{EXPIRES, HttpDate};
header! { header! {
/// `Expires` header, defined in [RFC7234](http://tools.ietf.org/html/rfc7234#section-5.3) /// `Expires` header, defined in [RFC7234](http://tools.ietf.org/html/rfc7234#section-5.3)
@ -23,14 +23,14 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::Expires; /// use actix_web::http::header::Expires;
/// use std::time::{SystemTime, Duration}; /// use std::time::{SystemTime, Duration};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// let expiration = SystemTime::now() + Duration::from_secs(60 * 60 * 24); /// let expiration = SystemTime::now() + Duration::from_secs(60 * 60 * 24);
/// builder.set(Expires(expiration.into())); /// builder.set(Expires(expiration.into()));
/// ``` /// ```
(Expires, http::EXPIRES) => [HttpDate] (Expires, EXPIRES) => [HttpDate]
test_expires { test_expires {
// Test case from RFC // Test case from RFC

View file

@ -1,4 +1,4 @@
use header::{http, EntityTag}; use header::{IF_MATCH, EntityTag};
header! { header! {
/// `If-Match` header, defined in /// `If-Match` header, defined in
@ -31,7 +31,7 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::IfMatch; /// use actix_web::http::header::IfMatch;
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// builder.set(IfMatch::Any); /// builder.set(IfMatch::Any);
@ -39,7 +39,7 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::{IfMatch, EntityTag}; /// use actix_web::http::header::{IfMatch, EntityTag};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// builder.set( /// builder.set(
@ -50,7 +50,7 @@ header! {
/// ]) /// ])
/// ); /// );
/// ``` /// ```
(IfMatch, http::IF_MATCH) => {Any / (EntityTag)+} (IfMatch, IF_MATCH) => {Any / (EntityTag)+}
test_if_match { test_if_match {
test_header!( test_header!(

View file

@ -1,4 +1,4 @@
use header::{http, HttpDate}; use header::{IF_MODIFIED_SINCE, HttpDate};
header! { header! {
/// `If-Modified-Since` header, defined in /// `If-Modified-Since` header, defined in
@ -23,14 +23,14 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::IfModifiedSince; /// use actix_web::http::header::IfModifiedSince;
/// use std::time::{SystemTime, Duration}; /// use std::time::{SystemTime, Duration};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24); /// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(IfModifiedSince(modified.into())); /// builder.set(IfModifiedSince(modified.into()));
/// ``` /// ```
(IfModifiedSince, http::IF_MODIFIED_SINCE) => [HttpDate] (IfModifiedSince, IF_MODIFIED_SINCE) => [HttpDate]
test_if_modified_since { test_if_modified_since {
// Test case from RFC // Test case from RFC

View file

@ -1,4 +1,4 @@
use header::{http, EntityTag}; use header::{IF_NONE_MATCH, EntityTag};
header! { header! {
/// `If-None-Match` header, defined in /// `If-None-Match` header, defined in
@ -33,7 +33,7 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::IfNoneMatch; /// use actix_web::http::header::IfNoneMatch;
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// builder.set(IfNoneMatch::Any); /// builder.set(IfNoneMatch::Any);
@ -41,7 +41,7 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::{IfNoneMatch, EntityTag}; /// use actix_web::http::header::{IfNoneMatch, EntityTag};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// builder.set( /// builder.set(
@ -52,7 +52,7 @@ header! {
/// ]) /// ])
/// ); /// );
/// ``` /// ```
(IfNoneMatch, http::IF_NONE_MATCH) => {Any / (EntityTag)+} (IfNoneMatch, IF_NONE_MATCH) => {Any / (EntityTag)+}
test_if_none_match { test_if_none_match {
test_header!(test1, vec![b"\"xyzzy\""]); test_header!(test1, vec![b"\"xyzzy\""]);
@ -67,18 +67,18 @@ header! {
mod tests { mod tests {
use super::IfNoneMatch; use super::IfNoneMatch;
use test::TestRequest; use test::TestRequest;
use header::{http, Header, EntityTag}; use header::{IF_NONE_MATCH, Header, EntityTag};
#[test] #[test]
fn test_if_none_match() { fn test_if_none_match() {
let mut if_none_match: Result<IfNoneMatch, _>; let mut if_none_match: Result<IfNoneMatch, _>;
let req = TestRequest::with_header(http::IF_NONE_MATCH, "*").finish(); let req = TestRequest::with_header(IF_NONE_MATCH, "*").finish();
if_none_match = Header::parse(&req); if_none_match = Header::parse(&req);
assert_eq!(if_none_match.ok(), Some(IfNoneMatch::Any)); assert_eq!(if_none_match.ok(), Some(IfNoneMatch::Any));
let req = TestRequest::with_header( let req = TestRequest::with_header(
http::IF_NONE_MATCH, &b"\"foobar\", W/\"weak-etag\""[..]).finish(); IF_NONE_MATCH, &b"\"foobar\", W/\"weak-etag\""[..]).finish();
if_none_match = Header::parse(&req); if_none_match = Header::parse(&req);
let mut entities: Vec<EntityTag> = Vec::new(); let mut entities: Vec<EntityTag> = Vec::new();

View file

@ -1,8 +1,10 @@
use std::fmt::{self, Display, Write}; use std::fmt::{self, Display, Write};
use error::ParseError; use error::ParseError;
use httpmessage::HttpMessage; use httpmessage::HttpMessage;
use header::{http, from_one_raw_str}; use http::header;
use header::{IntoHeaderValue, Header, EntityTag, HttpDate, Writer}; use header::from_one_raw_str;
use header::{IntoHeaderValue, Header, HeaderName, HeaderValue,
EntityTag, HttpDate, Writer, InvalidHeaderValueBytes};
/// `If-Range` header, defined in [RFC7233](http://tools.ietf.org/html/rfc7233#section-3.2) /// `If-Range` header, defined in [RFC7233](http://tools.ietf.org/html/rfc7233#section-3.2)
/// ///
@ -34,7 +36,7 @@ use header::{IntoHeaderValue, Header, EntityTag, HttpDate, Writer};
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::{IfRange, EntityTag}; /// use actix_web::http::header::{IfRange, EntityTag};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// builder.set(IfRange::EntityTag(EntityTag::new(false, "xyzzy".to_owned()))); /// builder.set(IfRange::EntityTag(EntityTag::new(false, "xyzzy".to_owned())));
@ -42,7 +44,7 @@ use header::{IntoHeaderValue, Header, EntityTag, HttpDate, Writer};
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::IfRange; /// use actix_web::http::header::IfRange;
/// use std::time::{SystemTime, Duration}; /// use std::time::{SystemTime, Duration};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
@ -58,17 +60,19 @@ pub enum IfRange {
} }
impl Header for IfRange { impl Header for IfRange {
fn name() -> http::HeaderName { fn name() -> HeaderName {
http::IF_RANGE header::IF_RANGE
} }
#[inline] #[inline]
fn parse<T>(msg: &T) -> Result<Self, ParseError> where T: HttpMessage fn parse<T>(msg: &T) -> Result<Self, ParseError> where T: HttpMessage
{ {
let etag: Result<EntityTag, _> = from_one_raw_str(msg.headers().get(http::IF_RANGE)); let etag: Result<EntityTag, _> =
from_one_raw_str(msg.headers().get(header::IF_RANGE));
if let Ok(etag) = etag { if let Ok(etag) = etag {
return Ok(IfRange::EntityTag(etag)); return Ok(IfRange::EntityTag(etag));
} }
let date: Result<HttpDate, _> = from_one_raw_str(msg.headers().get(http::IF_RANGE)); let date: Result<HttpDate, _> =
from_one_raw_str(msg.headers().get(header::IF_RANGE));
if let Ok(date) = date { if let Ok(date) = date {
return Ok(IfRange::Date(date)); return Ok(IfRange::Date(date));
} }
@ -86,12 +90,12 @@ impl Display for IfRange {
} }
impl IntoHeaderValue for IfRange { impl IntoHeaderValue for IfRange {
type Error = http::InvalidHeaderValueBytes; type Error = InvalidHeaderValueBytes;
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
let mut writer = Writer::new(); let mut writer = Writer::new();
let _ = write!(&mut writer, "{}", self); let _ = write!(&mut writer, "{}", self);
http::HeaderValue::from_shared(writer.take()) HeaderValue::from_shared(writer.take())
} }
} }

View file

@ -1,4 +1,4 @@
use header::{http, HttpDate}; use header::{IF_UNMODIFIED_SINCE, HttpDate};
header! { header! {
/// `If-Unmodified-Since` header, defined in /// `If-Unmodified-Since` header, defined in
@ -24,14 +24,14 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::IfUnmodifiedSince; /// use actix_web::http::header::IfUnmodifiedSince;
/// use std::time::{SystemTime, Duration}; /// use std::time::{SystemTime, Duration};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24); /// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(IfUnmodifiedSince(modified.into())); /// builder.set(IfUnmodifiedSince(modified.into()));
/// ``` /// ```
(IfUnmodifiedSince, http::IF_UNMODIFIED_SINCE) => [HttpDate] (IfUnmodifiedSince, IF_UNMODIFIED_SINCE) => [HttpDate]
test_if_unmodified_since { test_if_unmodified_since {
// Test case from RFC // Test case from RFC

View file

@ -1,4 +1,4 @@
use header::{http, HttpDate}; use header::{LAST_MODIFIED, HttpDate};
header! { header! {
/// `Last-Modified` header, defined in /// `Last-Modified` header, defined in
@ -23,14 +23,14 @@ header! {
/// ///
/// ```rust /// ```rust
/// use actix_web::httpcodes; /// use actix_web::httpcodes;
/// use actix_web::header::LastModified; /// use actix_web::http::header::LastModified;
/// use std::time::{SystemTime, Duration}; /// use std::time::{SystemTime, Duration};
/// ///
/// let mut builder = httpcodes::HttpOk.build(); /// let mut builder = httpcodes::HttpOk.build();
/// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24); /// let modified = SystemTime::now() - Duration::from_secs(60 * 60 * 24);
/// builder.set(LastModified(modified.into())); /// builder.set(LastModified(modified.into()));
/// ``` /// ```
(LastModified, http::LAST_MODIFIED) => [HttpDate] (LastModified, LAST_MODIFIED) => [HttpDate]
test_last_modified { test_last_modified {
// Test case from RFC // Test case from RFC

View file

@ -144,7 +144,7 @@ macro_rules! header {
__hyper__deref!($id => Vec<$item>); __hyper__deref!($id => Vec<$item>);
impl $crate::header::Header for $id { impl $crate::header::Header for $id {
#[inline] #[inline]
fn name() -> $crate::header::http::HeaderName { fn name() -> $crate::header::HeaderName {
$name $name
} }
#[inline] #[inline]
@ -162,13 +162,13 @@ macro_rules! header {
} }
} }
impl $crate::header::IntoHeaderValue for $id { impl $crate::header::IntoHeaderValue for $id {
type Error = $crate::header::http::InvalidHeaderValueBytes; type Error = $crate::header::InvalidHeaderValueBytes;
fn try_into(self) -> Result<$crate::header::http::HeaderValue, Self::Error> { fn try_into(self) -> Result<$crate::header::HeaderValue, Self::Error> {
use std::fmt::Write; use std::fmt::Write;
let mut writer = $crate::header::Writer::new(); let mut writer = $crate::header::Writer::new();
let _ = write!(&mut writer, "{}", self); let _ = write!(&mut writer, "{}", self);
$crate::header::http::HeaderValue::from_shared(writer.take()) $crate::header::HeaderValue::from_shared(writer.take())
} }
} }
}; };
@ -180,7 +180,7 @@ macro_rules! header {
__hyper__deref!($id => Vec<$item>); __hyper__deref!($id => Vec<$item>);
impl $crate::header::Header for $id { impl $crate::header::Header for $id {
#[inline] #[inline]
fn name() -> $crate::header::http::HeaderName { fn name() -> $crate::header::HeaderName {
$name $name
} }
#[inline] #[inline]
@ -198,13 +198,13 @@ macro_rules! header {
} }
} }
impl $crate::header::IntoHeaderValue for $id { impl $crate::header::IntoHeaderValue for $id {
type Error = $crate::header::http::InvalidHeaderValueBytes; type Error = $crate::header::InvalidHeaderValueBytes;
fn try_into(self) -> Result<$crate::header::http::HeaderValue, Self::Error> { fn try_into(self) -> Result<$crate::header::HeaderValue, Self::Error> {
use std::fmt::Write; use std::fmt::Write;
let mut writer = $crate::header::Writer::new(); let mut writer = $crate::header::Writer::new();
let _ = write!(&mut writer, "{}", self); let _ = write!(&mut writer, "{}", self);
$crate::header::http::HeaderValue::from_shared(writer.take()) $crate::header::HeaderValue::from_shared(writer.take())
} }
} }
}; };
@ -216,7 +216,7 @@ macro_rules! header {
__hyper__deref!($id => $value); __hyper__deref!($id => $value);
impl $crate::header::Header for $id { impl $crate::header::Header for $id {
#[inline] #[inline]
fn name() -> $crate::header::http::HeaderName { fn name() -> $crate::header::HeaderName {
$name $name
} }
#[inline] #[inline]
@ -234,9 +234,9 @@ macro_rules! header {
} }
} }
impl $crate::header::IntoHeaderValue for $id { impl $crate::header::IntoHeaderValue for $id {
type Error = $crate::header::http::InvalidHeaderValueBytes; type Error = $crate::header::InvalidHeaderValueBytes;
fn try_into(self) -> Result<$crate::header::http::HeaderValue, Self::Error> { fn try_into(self) -> Result<$crate::header::HeaderValue, Self::Error> {
self.0.try_into() self.0.try_into()
} }
} }
@ -253,12 +253,12 @@ macro_rules! header {
} }
impl $crate::header::Header for $id { impl $crate::header::Header for $id {
#[inline] #[inline]
fn name() -> $crate::header::http::HeaderName { fn name() -> $crate::header::HeaderName {
$name $name
} }
#[inline] #[inline]
fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError> fn parse<T>(msg: &T) -> Result<Self, $crate::error::ParseError>
where T: $crate::header::HttpMessage where T: $crate::HttpMessage
{ {
let any = msg.headers().get(Self::name()).and_then(|hdr| { let any = msg.headers().get(Self::name()).and_then(|hdr| {
hdr.to_str().ok().and_then(|hdr| Some(hdr.trim() == "*"))}); hdr.to_str().ok().and_then(|hdr| Some(hdr.trim() == "*"))});
@ -283,13 +283,13 @@ macro_rules! header {
} }
} }
impl $crate::header::IntoHeaderValue for $id { impl $crate::header::IntoHeaderValue for $id {
type Error = $crate::header::http::InvalidHeaderValueBytes; type Error = $crate::header::InvalidHeaderValueBytes;
fn try_into(self) -> Result<$crate::header::http::HeaderValue, Self::Error> { fn try_into(self) -> Result<$crate::header::HeaderValue, Self::Error> {
use std::fmt::Write; use std::fmt::Write;
let mut writer = $crate::header::Writer::new(); let mut writer = $crate::header::Writer::new();
let _ = write!(&mut writer, "{}", self); let _ = write!(&mut writer, "{}", self);
$crate::header::http::HeaderValue::from_shared(writer.take()) $crate::header::HeaderValue::from_shared(writer.take())
} }
} }
}; };

View file

@ -5,21 +5,15 @@ use std::fmt;
use std::str::FromStr; use std::str::FromStr;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use http::{Error as HttpError}; use modhttp::{Error as HttpError};
use http::header::GetAll; use modhttp::header::GetAll;
use mime::Mime; use mime::Mime;
pub use cookie::{Cookie, CookieBuilder};
pub use http_range::HttpRange;
#[doc(hidden)] #[doc(hidden)]
pub mod http { pub use modhttp::header::*;
pub use http::header::*;
}
use error::ParseError; use error::ParseError;
use httpmessage::HttpMessage; use httpmessage::HttpMessage;
pub use httpresponse::ConnectionType;
mod common; mod common;
mod shared; mod shared;
@ -34,7 +28,7 @@ pub use self::shared::*;
pub trait Header where Self: IntoHeaderValue { pub trait Header where Self: IntoHeaderValue {
/// Returns the name of the header field /// Returns the name of the header field
fn name() -> http::HeaderName; fn name() -> HeaderName;
/// Parse a header /// Parse a header
fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError>; fn parse<T: HttpMessage>(msg: &T) -> Result<Self, ParseError>;
@ -47,69 +41,69 @@ pub trait IntoHeaderValue: Sized {
type Error: Into<HttpError>; type Error: Into<HttpError>;
/// Cast from PyObject to a concrete Python object type. /// Cast from PyObject to a concrete Python object type.
fn try_into(self) -> Result<http::HeaderValue, Self::Error>; fn try_into(self) -> Result<HeaderValue, Self::Error>;
} }
impl IntoHeaderValue for http::HeaderValue { impl IntoHeaderValue for HeaderValue {
type Error = http::InvalidHeaderValue; type Error = InvalidHeaderValue;
#[inline] #[inline]
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
Ok(self) Ok(self)
} }
} }
impl<'a> IntoHeaderValue for &'a str { impl<'a> IntoHeaderValue for &'a str {
type Error = http::InvalidHeaderValue; type Error = InvalidHeaderValue;
#[inline] #[inline]
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
self.parse() self.parse()
} }
} }
impl<'a> IntoHeaderValue for &'a [u8] { impl<'a> IntoHeaderValue for &'a [u8] {
type Error = http::InvalidHeaderValue; type Error = InvalidHeaderValue;
#[inline] #[inline]
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
http::HeaderValue::from_bytes(self) HeaderValue::from_bytes(self)
} }
} }
impl IntoHeaderValue for Bytes { impl IntoHeaderValue for Bytes {
type Error = http::InvalidHeaderValueBytes; type Error = InvalidHeaderValueBytes;
#[inline] #[inline]
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
http::HeaderValue::from_shared(self) HeaderValue::from_shared(self)
} }
} }
impl IntoHeaderValue for Vec<u8> { impl IntoHeaderValue for Vec<u8> {
type Error = http::InvalidHeaderValueBytes; type Error = InvalidHeaderValueBytes;
#[inline] #[inline]
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
http::HeaderValue::from_shared(Bytes::from(self)) HeaderValue::from_shared(Bytes::from(self))
} }
} }
impl IntoHeaderValue for String { impl IntoHeaderValue for String {
type Error = http::InvalidHeaderValueBytes; type Error = InvalidHeaderValueBytes;
#[inline] #[inline]
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
http::HeaderValue::from_shared(Bytes::from(self)) HeaderValue::from_shared(Bytes::from(self))
} }
} }
impl IntoHeaderValue for Mime { impl IntoHeaderValue for Mime {
type Error = http::InvalidHeaderValueBytes; type Error = InvalidHeaderValueBytes;
#[inline] #[inline]
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
http::HeaderValue::from_shared(Bytes::from(format!("{}", self))) HeaderValue::from_shared(Bytes::from(format!("{}", self)))
} }
} }
@ -206,7 +200,7 @@ impl fmt::Write for Writer {
#[inline] #[inline]
#[doc(hidden)] #[doc(hidden)]
/// Reads a comma-delimited raw header into a Vec. /// Reads a comma-delimited raw header into a Vec.
pub fn from_comma_delimited<T: FromStr>(all: GetAll<http::HeaderValue>) pub fn from_comma_delimited<T: FromStr>(all: GetAll<HeaderValue>)
-> Result<Vec<T>, ParseError> -> Result<Vec<T>, ParseError>
{ {
let mut result = Vec::new(); let mut result = Vec::new();
@ -225,7 +219,7 @@ pub fn from_comma_delimited<T: FromStr>(all: GetAll<http::HeaderValue>)
#[inline] #[inline]
#[doc(hidden)] #[doc(hidden)]
/// Reads a single string when parsing a header. /// Reads a single string when parsing a header.
pub fn from_one_raw_str<T: FromStr>(val: Option<&http::HeaderValue>) pub fn from_one_raw_str<T: FromStr>(val: Option<&HeaderValue>)
-> Result<T, ParseError> -> Result<T, ParseError>
{ {
if let Some(line) = val { if let Some(line) = val {

View file

@ -1,6 +1,6 @@
use std::str::FromStr; use std::str::FromStr;
use std::fmt::{self, Display, Write}; use std::fmt::{self, Display, Write};
use header::{http, Writer, IntoHeaderValue}; use header::{HeaderValue, Writer, IntoHeaderValue, InvalidHeaderValueBytes};
/// check that each char in the slice is either: /// check that each char in the slice is either:
/// 1. `%x21`, or /// 1. `%x21`, or
@ -144,12 +144,12 @@ impl FromStr for EntityTag {
} }
impl IntoHeaderValue for EntityTag { impl IntoHeaderValue for EntityTag {
type Error = http::InvalidHeaderValueBytes; type Error = InvalidHeaderValueBytes;
fn try_into(self) -> Result<http::HeaderValue, Self::Error> { fn try_into(self) -> Result<HeaderValue, Self::Error> {
let mut wrt = Writer::new(); let mut wrt = Writer::new();
write!(wrt, "{}", self).unwrap(); write!(wrt, "{}", self).unwrap();
unsafe{Ok(http::HeaderValue::from_shared_unchecked(wrt.take()))} unsafe{Ok(HeaderValue::from_shared_unchecked(wrt.take()))}
} }
} }

View file

@ -34,7 +34,7 @@ use httpresponse::HttpResponse;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// # use actix_web::*; /// # use actix_web::*;
/// use actix_web::helpers::NormalizePath; /// use actix_web::http::NormalizePath;
/// # /// #
/// # fn index(req: HttpRequest) -> httpcodes::StaticResponse { /// # fn index(req: HttpRequest) -> httpcodes::StaticResponse {
/// # httpcodes::HttpOk /// # httpcodes::HttpOk

View file

@ -71,113 +71,6 @@ pub const HttpInsufficientStorage: StaticResponse =
StaticResponse(StatusCode::INSUFFICIENT_STORAGE); StaticResponse(StatusCode::INSUFFICIENT_STORAGE);
pub const HttpLoopDetected: StaticResponse = StaticResponse(StatusCode::LOOP_DETECTED); pub const HttpLoopDetected: StaticResponse = StaticResponse(StatusCode::LOOP_DETECTED);
#[doc(hidden)]
pub const HTTPOk: StaticResponse = StaticResponse(StatusCode::OK);
#[doc(hidden)]
pub const HTTPCreated: StaticResponse = StaticResponse(StatusCode::CREATED);
#[doc(hidden)]
pub const HTTPAccepted: StaticResponse = StaticResponse(StatusCode::ACCEPTED);
#[doc(hidden)]
pub const HTTPNonAuthoritativeInformation: StaticResponse =
StaticResponse(StatusCode::NON_AUTHORITATIVE_INFORMATION);
#[doc(hidden)]
pub const HTTPNoContent: StaticResponse = StaticResponse(StatusCode::NO_CONTENT);
#[doc(hidden)]
pub const HTTPResetContent: StaticResponse = StaticResponse(StatusCode::RESET_CONTENT);
#[doc(hidden)]
pub const HTTPPartialContent: StaticResponse = StaticResponse(StatusCode::PARTIAL_CONTENT);
#[doc(hidden)]
pub const HTTPMultiStatus: StaticResponse = StaticResponse(StatusCode::MULTI_STATUS);
#[doc(hidden)]
pub const HTTPAlreadyReported: StaticResponse = StaticResponse(StatusCode::ALREADY_REPORTED);
#[doc(hidden)]
pub const HTTPMultipleChoices: StaticResponse = StaticResponse(StatusCode::MULTIPLE_CHOICES);
#[doc(hidden)]
pub const HTTPMovedPermanenty: StaticResponse = StaticResponse(StatusCode::MOVED_PERMANENTLY);
#[doc(hidden)]
pub const HTTPFound: StaticResponse = StaticResponse(StatusCode::FOUND);
#[doc(hidden)]
pub const HTTPSeeOther: StaticResponse = StaticResponse(StatusCode::SEE_OTHER);
#[doc(hidden)]
pub const HTTPNotModified: StaticResponse = StaticResponse(StatusCode::NOT_MODIFIED);
#[doc(hidden)]
pub const HTTPUseProxy: StaticResponse = StaticResponse(StatusCode::USE_PROXY);
#[doc(hidden)]
pub const HTTPTemporaryRedirect: StaticResponse =
StaticResponse(StatusCode::TEMPORARY_REDIRECT);
#[doc(hidden)]
pub const HTTPPermanentRedirect: StaticResponse =
StaticResponse(StatusCode::PERMANENT_REDIRECT);
#[doc(hidden)]
pub const HTTPBadRequest: StaticResponse = StaticResponse(StatusCode::BAD_REQUEST);
#[doc(hidden)]
pub const HTTPUnauthorized: StaticResponse = StaticResponse(StatusCode::UNAUTHORIZED);
#[doc(hidden)]
pub const HTTPPaymentRequired: StaticResponse = StaticResponse(StatusCode::PAYMENT_REQUIRED);
#[doc(hidden)]
pub const HTTPForbidden: StaticResponse = StaticResponse(StatusCode::FORBIDDEN);
#[doc(hidden)]
pub const HTTPNotFound: StaticResponse = StaticResponse(StatusCode::NOT_FOUND);
#[doc(hidden)]
pub const HTTPMethodNotAllowed: StaticResponse =
StaticResponse(StatusCode::METHOD_NOT_ALLOWED);
#[doc(hidden)]
pub const HTTPNotAcceptable: StaticResponse = StaticResponse(StatusCode::NOT_ACCEPTABLE);
#[doc(hidden)]
pub const HTTPProxyAuthenticationRequired: StaticResponse =
StaticResponse(StatusCode::PROXY_AUTHENTICATION_REQUIRED);
#[doc(hidden)]
pub const HTTPRequestTimeout: StaticResponse = StaticResponse(StatusCode::REQUEST_TIMEOUT);
#[doc(hidden)]
pub const HTTPConflict: StaticResponse = StaticResponse(StatusCode::CONFLICT);
#[doc(hidden)]
pub const HTTPGone: StaticResponse = StaticResponse(StatusCode::GONE);
#[doc(hidden)]
pub const HTTPLengthRequired: StaticResponse = StaticResponse(StatusCode::LENGTH_REQUIRED);
#[doc(hidden)]
pub const HTTPPreconditionFailed: StaticResponse =
StaticResponse(StatusCode::PRECONDITION_FAILED);
#[doc(hidden)]
pub const HTTPPayloadTooLarge: StaticResponse = StaticResponse(StatusCode::PAYLOAD_TOO_LARGE);
#[doc(hidden)]
pub const HTTPUriTooLong: StaticResponse = StaticResponse(StatusCode::URI_TOO_LONG);
#[doc(hidden)]
pub const HTTPUnsupportedMediaType: StaticResponse =
StaticResponse(StatusCode::UNSUPPORTED_MEDIA_TYPE);
#[doc(hidden)]
pub const HTTPRangeNotSatisfiable: StaticResponse =
StaticResponse(StatusCode::RANGE_NOT_SATISFIABLE);
#[doc(hidden)]
pub const HTTPExpectationFailed: StaticResponse =
StaticResponse(StatusCode::EXPECTATION_FAILED);
#[doc(hidden)]
pub const HTTPInternalServerError: StaticResponse =
StaticResponse(StatusCode::INTERNAL_SERVER_ERROR);
#[doc(hidden)]
pub const HTTPNotImplemented: StaticResponse = StaticResponse(StatusCode::NOT_IMPLEMENTED);
#[doc(hidden)]
pub const HTTPBadGateway: StaticResponse = StaticResponse(StatusCode::BAD_GATEWAY);
#[doc(hidden)]
pub const HTTPServiceUnavailable: StaticResponse =
StaticResponse(StatusCode::SERVICE_UNAVAILABLE);
#[doc(hidden)]
pub const HTTPGatewayTimeout: StaticResponse =
StaticResponse(StatusCode::GATEWAY_TIMEOUT);
#[doc(hidden)]
pub const HTTPVersionNotSupported: StaticResponse =
StaticResponse(StatusCode::HTTP_VERSION_NOT_SUPPORTED);
#[doc(hidden)]
pub const HTTPVariantAlsoNegotiates: StaticResponse =
StaticResponse(StatusCode::VARIANT_ALSO_NEGOTIATES);
#[doc(hidden)]
pub const HTTPInsufficientStorage: StaticResponse =
StaticResponse(StatusCode::INSUFFICIENT_STORAGE);
#[doc(hidden)]
pub const HTTPLoopDetected: StaticResponse = StaticResponse(StatusCode::LOOP_DETECTED);
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub struct StaticResponse(StatusCode); pub struct StaticResponse(StatusCode);
@ -281,32 +174,32 @@ impl HttpResponse {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use http::StatusCode; use http::StatusCode;
use super::{HTTPOk, HTTPBadRequest, Body, HttpResponse}; use super::{HttpOk, HttpBadRequest, Body, HttpResponse};
#[test] #[test]
fn test_build() { fn test_build() {
let resp = HTTPOk.build().body(Body::Empty).unwrap(); let resp = HttpOk.build().body(Body::Empty).unwrap();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
#[test] #[test]
fn test_response() { fn test_response() {
let resp: HttpResponse = HTTPOk.into(); let resp: HttpResponse = HttpOk.into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
#[test] #[test]
fn test_from() { fn test_from() {
let resp: HttpResponse = HTTPOk.into(); let resp: HttpResponse = HttpOk.into();
assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.status(), StatusCode::OK);
} }
#[test] #[test]
fn test_with_reason() { fn test_with_reason() {
let resp: HttpResponse = HTTPOk.into(); let resp: HttpResponse = HttpOk.into();
assert_eq!(resp.reason(), "OK"); assert_eq!(resp.reason(), "OK");
let resp = HTTPBadRequest.with_reason("test"); let resp = HttpBadRequest.with_reason("test");
assert_eq!(resp.status(), StatusCode::BAD_REQUEST); assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
assert_eq!(resp.reason(), "test"); assert_eq!(resp.reason(), "test");
} }

View file

@ -240,7 +240,7 @@ pub trait HttpMessage {
/// } /// }
/// }) /// })
/// .finish() // <- Stream::finish() combinator from actix /// .finish() // <- Stream::finish() combinator from actix
/// .map(|_| httpcodes::HTTPOk.into()) /// .map(|_| httpcodes::HttpOk.into())
/// .responder() /// .responder()
/// } /// }
/// # fn main() {} /// # fn main() {}

View file

@ -279,8 +279,8 @@ impl<S> HttpRequest<S> {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// # use actix_web::{Application, HttpRequest, HttpResponse, http};
/// # use actix_web::httpcodes::*; /// # use actix_web::httpcodes::HttpOk;
/// # /// #
/// fn index(req: HttpRequest) -> HttpResponse { /// fn index(req: HttpRequest) -> HttpResponse {
/// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource /// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
@ -291,7 +291,7 @@ impl<S> HttpRequest<S> {
/// let app = Application::new() /// let app = Application::new()
/// .resource("/test/{one}/{two}/{three}", |r| { /// .resource("/test/{one}/{two}/{three}", |r| {
/// r.name("foo"); // <- set resource name, then it could be used in `url_for` /// r.name("foo"); // <- set resource name, then it could be used in `url_for`
/// r.method(Method::GET).f(|_| httpcodes::HttpOk); /// r.method(http::Method::GET).f(|_| HttpOk);
/// }) /// })
/// .finish(); /// .finish();
/// } /// }

View file

@ -283,14 +283,11 @@ impl HttpResponseBuilder {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// use actix_web::{HttpRequest, HttpResponse, Result, http, httpcodes};
/// # use actix_web::httpcodes::*;
/// #
/// use actix_web::header;
/// ///
/// fn index(req: HttpRequest) -> Result<HttpResponse> { /// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(HttpOk.build() /// Ok(httpcodes::HttpOk.build()
/// .set(header::IfModifiedSince("Sun, 07 Nov 1994 08:48:37 GMT".parse()?)) /// .set(http::header::IfModifiedSince("Sun, 07 Nov 1994 08:48:37 GMT".parse()?))
/// .finish()?) /// .finish()?)
/// } /// }
/// fn main() {} /// fn main() {}
@ -432,15 +429,12 @@ impl HttpResponseBuilder {
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// # use actix_web::*; /// use actix_web::{HttpRequest, HttpResponse, Result, http, httpcodes};
/// # use actix_web::httpcodes::*;
/// #
/// use actix_web::header::Cookie;
/// ///
/// fn index(req: HttpRequest) -> Result<HttpResponse> { /// fn index(req: HttpRequest) -> Result<HttpResponse> {
/// Ok(HttpOk.build() /// Ok(httpcodes::HttpOk.build()
/// .cookie( /// .cookie(
/// Cookie::build("name", "value") /// http::Cookie::build("name", "value")
/// .domain("www.rust-lang.org") /// .domain("www.rust-lang.org")
/// .path("/") /// .path("/")
/// .secure(true) /// .secure(true)
@ -876,7 +870,7 @@ mod tests {
use http::{Method, Uri}; use http::{Method, Uri};
use http::header::{COOKIE, CONTENT_TYPE, HeaderValue}; use http::header::{COOKIE, CONTENT_TYPE, HeaderValue};
use body::Binary; use body::Binary;
use {header, httpcodes}; use {http, httpcodes};
#[test] #[test]
fn test_debug() { fn test_debug() {
@ -900,7 +894,7 @@ mod tests {
let resp = httpcodes::HttpOk let resp = httpcodes::HttpOk
.build() .build()
.cookie(header::Cookie::build("name", "value") .cookie(http::Cookie::build("name", "value")
.domain("www.rust-lang.org") .domain("www.rust-lang.org")
.path("/test") .path("/test")
.http_only(true) .http_only(true)

View file

@ -51,8 +51,7 @@ use httpresponse::HttpResponse;
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// # use actix_web::*; /// use actix_web::{Application, Json, Result, http};
/// use actix_web::Json;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -67,7 +66,7 @@ use httpresponse::HttpResponse;
/// fn main() { /// fn main() {
/// let app = Application::new().resource( /// let app = Application::new().resource(
/// "/index.html", /// "/index.html",
/// |r| r.method(Method::POST).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::POST).with(index)); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub struct Json<T>(pub T); pub struct Json<T>(pub T);
@ -139,8 +138,9 @@ impl<T, S> FromRequest<S> for Json<T>
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// # #[macro_use] extern crate serde_derive; /// # #[macro_use] extern crate serde_derive;
/// use actix_web::*;
/// use futures::future::Future; /// use futures::future::Future;
/// use actix_web::{Application, AsyncResponder,
/// HttpRequest, HttpResponse, HttpMessage, Error, httpcodes};
/// ///
/// #[derive(Deserialize, Debug)] /// #[derive(Deserialize, Debug)]
/// struct MyObj { /// struct MyObj {

View file

@ -67,7 +67,7 @@ extern crate tokio_core;
extern crate mio; extern crate mio;
extern crate net2; extern crate net2;
extern crate cookie; extern crate cookie;
extern crate http; extern crate http as modhttp;
extern crate httparse; extern crate httparse;
extern crate http_range; extern crate http_range;
extern crate mime; extern crate mime;
@ -108,6 +108,8 @@ mod body;
mod context; mod context;
mod de; mod de;
mod handler; mod handler;
mod header;
mod helpers;
mod httpmessage; mod httpmessage;
mod httprequest; mod httprequest;
mod httpresponse; mod httpresponse;
@ -125,8 +127,6 @@ pub mod client;
pub mod fs; pub mod fs;
pub mod ws; pub mod ws;
pub mod error; pub mod error;
pub mod header;
pub mod helpers;
pub mod httpcodes; pub mod httpcodes;
pub mod multipart; pub mod multipart;
pub mod middleware; pub mod middleware;
@ -145,9 +145,6 @@ pub use handler::{Either, Responder, AsyncResponder, FutureResponse, State};
pub use context::HttpContext; pub use context::HttpContext;
pub use server::HttpServer; pub use server::HttpServer;
// re-exports
pub use http::{Method, StatusCode};
#[cfg(feature="openssl")] #[cfg(feature="openssl")]
pub(crate) const HAS_OPENSSL: bool = true; pub(crate) const HAS_OPENSSL: bool = true;
#[cfg(not(feature="openssl"))] #[cfg(not(feature="openssl"))]
@ -182,3 +179,24 @@ pub mod dev {
pub use httpmessage::{UrlEncoded, MessageBody}; pub use httpmessage::{UrlEncoded, MessageBody};
pub use httpresponse::HttpResponseBuilder; pub use httpresponse::HttpResponseBuilder;
} }
pub mod http {
//! Various http related types
// re-exports
pub use modhttp::{Method, StatusCode, Version};
#[doc(hidden)]
pub use modhttp::{uri, Uri, Error, Extensions, HeaderMap, HttpTryFrom};
pub use http_range::HttpRange;
pub use cookie::{Cookie, CookieBuilder};
pub use helpers::NormalizePath;
pub mod header {
pub use ::header::*;
}
pub use header::ContentEncoding;
pub use httpresponse::ConnectionType;
}

View file

@ -17,10 +17,8 @@
//! # Example //! # Example
//! //!
//! ```rust //! ```rust
//! # extern crate http;
//! # extern crate actix_web; //! # extern crate actix_web;
//! # use actix_web::*; //! use actix_web::{Application, HttpRequest, http, httpcodes};
//! use http::header;
//! use actix_web::middleware::cors; //! use actix_web::middleware::cors;
//! //!
//! fn index(mut req: HttpRequest) -> &'static str { //! fn index(mut req: HttpRequest) -> &'static str {
@ -33,13 +31,13 @@
//! cors::Cors::build() // <- Construct CORS middleware //! cors::Cors::build() // <- Construct CORS middleware
//! .allowed_origin("https://www.rust-lang.org/") //! .allowed_origin("https://www.rust-lang.org/")
//! .allowed_methods(vec!["GET", "POST"]) //! .allowed_methods(vec!["GET", "POST"])
//! .allowed_headers(vec![header::AUTHORIZATION, header::ACCEPT]) //! .allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
//! .allowed_header(header::CONTENT_TYPE) //! .allowed_header(http::header::CONTENT_TYPE)
//! .max_age(3600) //! .max_age(3600)
//! .finish().expect("Can not create CORS middleware") //! .finish().expect("Can not create CORS middleware")
//! .register(r); // <- Register CORS middleware //! .register(r); // <- Register CORS middleware
//! r.method(Method::GET).f(|_| httpcodes::HttpOk); //! r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
//! r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed); //! r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
//! }) //! })
//! .finish(); //! .finish();
//! } //! }

View file

@ -22,11 +22,10 @@
//! //!
//! ``` //! ```
//! # extern crate actix_web; //! # extern crate actix_web;
//! # use actix_web::*; //! use actix_web::{Application, HttpRequest, http, httpcodes};
//!
//! use actix_web::middleware::csrf; //! use actix_web::middleware::csrf;
//! //!
//! fn handle_post(_req: HttpRequest) -> &'static str { //! fn handle_post(_: HttpRequest) -> &'static str {
//! "This action should only be triggered with requests from the same site" //! "This action should only be triggered with requests from the same site"
//! } //! }
//! //!
@ -37,8 +36,8 @@
//! .allowed_origin("https://www.example.com") //! .allowed_origin("https://www.example.com")
//! .finish()) //! .finish())
//! .resource("/", |r| { //! .resource("/", |r| {
//! r.method(Method::GET).f(|_| httpcodes::HttpOk); //! r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
//! r.method(Method::POST).f(handle_post); //! r.method(http::Method::POST).f(handle_post);
//! }) //! })
//! .finish(); //! .finish();
//! } //! }

View file

@ -13,7 +13,7 @@ use middleware::{Response, Middleware};
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::*; /// use actix_web::{Application, http, httpcodes, middleware};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = Application::new()
@ -22,8 +22,8 @@ use middleware::{Response, Middleware};
/// .header("X-Version", "0.2") /// .header("X-Version", "0.2")
/// .finish()) /// .finish())
/// .resource("/test", |r| { /// .resource("/test", |r| {
/// r.method(Method::GET).f(|_| httpcodes::HttpOk); /// r.method(http::Method::GET).f(|_| httpcodes::HttpOk);
/// r.method(Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed); /// r.method(http::Method::HEAD).f(|_| httpcodes::HttpMethodNotAllowed);
/// }) /// })
/// .finish(); /// .finish();
/// } /// }

View file

@ -25,12 +25,12 @@ use with::WithHandler;
/// ///
/// ```rust /// ```rust
/// # extern crate actix_web; /// # extern crate actix_web;
/// use actix_web::*; /// use actix_web::{Application, HttpResponse, http};
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new() /// let app = Application::new()
/// .resource( /// .resource(
/// "/", |r| r.method(Method::GET).f(|r| HttpResponse::Ok())) /// "/", |r| r.method(http::Method::GET).f(|r| HttpResponse::Ok()))
/// .finish(); /// .finish();
/// } /// }
pub struct Resource<S=()> { pub struct Resource<S=()> {

View file

@ -110,8 +110,7 @@ impl<S: 'static> Route<S> {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::*; /// use actix_web::{Application, Path, Result, http};
/// use actix_web::Path;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct Info { /// struct Info {
@ -125,8 +124,8 @@ impl<S: 'static> Route<S> {
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new().resource( /// let app = Application::new().resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(Method::GET).with(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with(index)); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub fn with<T, H>(&mut self, handler: H) pub fn with<T, H>(&mut self, handler: H)
@ -143,8 +142,7 @@ impl<S: 'static> Route<S> {
/// # extern crate actix_web; /// # extern crate actix_web;
/// # extern crate futures; /// # extern crate futures;
/// #[macro_use] extern crate serde_derive; /// #[macro_use] extern crate serde_derive;
/// use actix_web::*; /// use actix_web::{Application, Query, Path, Result, http};
/// use actix_web::Path;
/// ///
/// #[derive(Deserialize)] /// #[derive(Deserialize)]
/// struct PParam { /// struct PParam {
@ -163,8 +161,8 @@ impl<S: 'static> Route<S> {
/// ///
/// fn main() { /// fn main() {
/// let app = Application::new().resource( /// let app = Application::new().resource(
/// "/{username}/index.html", // <- define path parameters /// "/{username}/index.html", // <- define path parameters
/// |r| r.method(Method::GET).with2(index)); // <- use `with` extractor /// |r| r.method(http::Method::GET).with2(index)); // <- use `with` extractor
/// } /// }
/// ``` /// ```
pub fn with2<T1, T2, F, R>(&mut self, handler: F) pub fn with2<T1, T2, F, R>(&mut self, handler: F)

View file

@ -8,7 +8,7 @@ use std::net::SocketAddr;
use std::collections::VecDeque; use std::collections::VecDeque;
use actix::Arbiter; use actix::Arbiter;
use http::request::Parts; use modhttp::request::Parts;
use http2::{Reason, RecvStream}; use http2::{Reason, RecvStream};
use http2::server::{self, Connection, Handshake, SendResponse}; use http2::server::{self, Connection, Handshake, SendResponse};
use bytes::{Buf, Bytes}; use bytes::{Buf, Bytes};

View file

@ -6,7 +6,9 @@ use bytes::{Bytes, BytesMut};
use futures::{Async, Poll}; use futures::{Async, Poll};
use http2::{Reason, SendStream}; use http2::{Reason, SendStream};
use http2::server::SendResponse; use http2::server::SendResponse;
use http::{Version, HttpTryFrom, Response}; use modhttp::Response;
use http::{Version, HttpTryFrom};
use http::header::{HeaderValue, CONNECTION, TRANSFER_ENCODING, DATE, CONTENT_LENGTH}; use http::header::{HeaderValue, CONNECTION, TRANSFER_ENCODING, DATE, CONTENT_LENGTH};
use body::{Body, Binary}; use body::{Body, Binary};

View file

@ -43,7 +43,7 @@ const STR: &str =
#[test] #[test]
fn test_simple() { fn test_simple() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| httpcodes::HTTPOk.build().body(STR))); |app| app.handler(|_| httpcodes::HttpOk.build().body(STR)));
let request = srv.get().header("x-test", "111").finish().unwrap(); let request = srv.get().header("x-test", "111").finish().unwrap();
let repr = format!("{:?}", request); let repr = format!("{:?}", request);
@ -70,8 +70,8 @@ fn test_simple() {
fn test_with_query_parameter() { fn test_with_query_parameter() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|req: HttpRequest| match req.query().get("qp") { |app| app.handler(|req: HttpRequest| match req.query().get("qp") {
Some(_) => httpcodes::HTTPOk.build().finish(), Some(_) => httpcodes::HttpOk.build().finish(),
None => httpcodes::HTTPBadRequest.build().finish(), None => httpcodes::HttpBadRequest.build().finish(),
})); }));
let request = srv.get().uri(srv.url("/?qp=5").as_str()).finish().unwrap(); let request = srv.get().uri(srv.url("/?qp=5").as_str()).finish().unwrap();
@ -84,7 +84,7 @@ fn test_with_query_parameter() {
#[test] #[test]
fn test_no_decompress() { fn test_no_decompress() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| httpcodes::HTTPOk.build().body(STR))); |app| app.handler(|_| httpcodes::HttpOk.build().body(STR)));
let request = srv.get().disable_decompress().finish().unwrap(); let request = srv.get().disable_decompress().finish().unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
@ -114,16 +114,16 @@ fn test_client_gzip_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Deflate) .content_encoding(http::ContentEncoding::Deflate)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
// client request // client request
let request = srv.post() let request = srv.post()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(STR).unwrap(); .body(STR).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -140,16 +140,16 @@ fn test_client_gzip_encoding_large() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Deflate) .content_encoding(http::ContentEncoding::Deflate)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
// client request // client request
let request = srv.post() let request = srv.post()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(data.clone()).unwrap(); .body(data.clone()).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -169,16 +169,16 @@ fn test_client_gzip_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Deflate) .content_encoding(http::ContentEncoding::Deflate)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
// client request // client request
let request = srv.post() let request = srv.post()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(data.clone()).unwrap(); .body(data.clone()).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -194,16 +194,16 @@ fn test_client_brotli_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
// client request // client request
let request = srv.client(Method::POST, "/") let request = srv.client(http::Method::POST, "/")
.content_encoding(header::ContentEncoding::Br) .content_encoding(http::ContentEncoding::Br)
.body(STR).unwrap(); .body(STR).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -224,16 +224,16 @@ fn test_client_brotli_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(move |bytes: Bytes| { .and_then(move |bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
// client request // client request
let request = srv.client(Method::POST, "/") let request = srv.client(http::Method::POST, "/")
.content_encoding(header::ContentEncoding::Br) .content_encoding(http::ContentEncoding::Br)
.body(data.clone()).unwrap(); .body(data.clone()).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -250,16 +250,16 @@ fn test_client_deflate_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Br) .content_encoding(http::ContentEncoding::Br)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
// client request // client request
let request = srv.post() let request = srv.post()
.content_encoding(header::ContentEncoding::Deflate) .content_encoding(http::ContentEncoding::Deflate)
.body(STR).unwrap(); .body(STR).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -280,16 +280,16 @@ fn test_client_deflate_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Br) .content_encoding(http::ContentEncoding::Br)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
// client request // client request
let request = srv.post() let request = srv.post()
.content_encoding(header::ContentEncoding::Deflate) .content_encoding(http::ContentEncoding::Deflate)
.body(data.clone()).unwrap(); .body(data.clone()).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -306,9 +306,9 @@ fn test_client_streaming_explicit() {
|req: HttpRequest| req.body() |req: HttpRequest| req.body()
.map_err(Error::from) .map_err(Error::from)
.and_then(|body| { .and_then(|body| {
Ok(httpcodes::HTTPOk.build() Ok(httpcodes::HttpOk.build()
.chunked() .chunked()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(body)?)}) .body(body)?)})
.responder())); .responder()));
@ -328,8 +328,8 @@ fn test_body_streaming_implicit() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| { |app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref()))); let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(Body::Streaming(Box::new(body)))})); .body(Body::Streaming(Box::new(body)))}));
let request = srv.get().finish().unwrap(); let request = srv.get().finish().unwrap();
@ -343,7 +343,7 @@ fn test_body_streaming_implicit() {
#[test] #[test]
fn test_client_cookie_handling() { fn test_client_cookie_handling() {
use actix_web::header::Cookie; use actix_web::http::Cookie;
fn err() -> Error { fn err() -> Error {
use std::io::{ErrorKind, Error as IoError}; use std::io::{ErrorKind, Error as IoError};
// stub some generic error // stub some generic error
@ -379,7 +379,7 @@ fn test_client_cookie_handling() {
}) })
// Send some cookies back // Send some cookies back
.map(|_| .map(|_|
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.cookie(cookie1.clone()) .cookie(cookie1.clone())
.cookie(cookie2.clone()) .cookie(cookie2.clone())
.finish() .finish()

View file

@ -3,7 +3,7 @@ extern crate actix_web;
extern crate tokio_core; extern crate tokio_core;
extern crate futures; extern crate futures;
extern crate h2; extern crate h2;
extern crate http; extern crate http as modhttp;
extern crate bytes; extern crate bytes;
extern crate flate2; extern crate flate2;
extern crate rand; extern crate rand;
@ -24,7 +24,7 @@ use futures::{Future, Stream};
use futures::stream::once; use futures::stream::once;
use h2::client as h2client; use h2::client as h2client;
use bytes::{Bytes, BytesMut}; use bytes::{Bytes, BytesMut};
use http::Request; use modhttp::Request;
use tokio_core::net::TcpStream; use tokio_core::net::TcpStream;
use tokio_core::reactor::Core; use tokio_core::reactor::Core;
use rand::Rng; use rand::Rng;
@ -65,7 +65,7 @@ fn test_start() {
let sys = System::new("test"); let sys = System::new("test");
let srv = HttpServer::new( let srv = HttpServer::new(
|| vec![Application::new() || vec![Application::new()
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))]); .resource("/", |r| r.method(http::Method::GET).h(httpcodes::HttpOk))]);
let srv = srv.bind("127.0.0.1:0").unwrap(); let srv = srv.bind("127.0.0.1:0").unwrap();
let addr = srv.addrs()[0]; let addr = srv.addrs()[0];
@ -108,7 +108,7 @@ fn test_shutdown() {
let sys = System::new("test"); let sys = System::new("test");
let srv = HttpServer::new( let srv = HttpServer::new(
|| vec![Application::new() || vec![Application::new()
.resource("/", |r| r.method(Method::GET).h(httpcodes::HTTPOk))]); .resource("/", |r| r.method(http::Method::GET).h(httpcodes::HttpOk))]);
let srv = srv.bind("127.0.0.1:0").unwrap(); let srv = srv.bind("127.0.0.1:0").unwrap();
let addr = srv.addrs()[0]; let addr = srv.addrs()[0];
@ -133,7 +133,7 @@ fn test_shutdown() {
#[test] #[test]
fn test_simple() { fn test_simple() {
let mut srv = test::TestServer::new(|app| app.handler(httpcodes::HTTPOk)); let mut srv = test::TestServer::new(|app| app.handler(httpcodes::HttpOk));
let req = srv.get().finish().unwrap(); let req = srv.get().finish().unwrap();
let response = srv.execute(req.send()).unwrap(); let response = srv.execute(req.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -147,7 +147,7 @@ fn test_headers() {
move |app| { move |app| {
let data = srv_data.clone(); let data = srv_data.clone();
app.handler(move |_| { app.handler(move |_| {
let mut builder = httpcodes::HTTPOk.build(); let mut builder = httpcodes::HttpOk.build();
for idx in 0..90 { for idx in 0..90 {
builder.header( builder.header(
format!("X-TEST-{}", idx).as_str(), format!("X-TEST-{}", idx).as_str(),
@ -180,7 +180,7 @@ fn test_headers() {
#[test] #[test]
fn test_body() { fn test_body() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| httpcodes::HTTPOk.build().body(STR))); |app| app.handler(|_| httpcodes::HttpOk.build().body(STR)));
let request = srv.get().finish().unwrap(); let request = srv.get().finish().unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
@ -195,8 +195,8 @@ fn test_body() {
fn test_body_gzip() { fn test_body_gzip() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler( |app| app.handler(
|_| httpcodes::HTTPOk.build() |_| httpcodes::HttpOk.build()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(STR))); .body(STR)));
let request = srv.get().disable_decompress().finish().unwrap(); let request = srv.get().disable_decompress().finish().unwrap();
@ -222,8 +222,8 @@ fn test_body_gzip_large() {
move |app| { move |app| {
let data = srv_data.clone(); let data = srv_data.clone();
app.handler( app.handler(
move |_| httpcodes::HTTPOk.build() move |_| httpcodes::HttpOk.build()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(data.as_ref()))}); .body(data.as_ref()))});
let request = srv.get().disable_decompress().finish().unwrap(); let request = srv.get().disable_decompress().finish().unwrap();
@ -252,8 +252,8 @@ fn test_body_gzip_large_random() {
move |app| { move |app| {
let data = srv_data.clone(); let data = srv_data.clone();
app.handler( app.handler(
move |_| httpcodes::HTTPOk.build() move |_| httpcodes::HttpOk.build()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(data.as_ref()))}); .body(data.as_ref()))});
let request = srv.get().disable_decompress().finish().unwrap(); let request = srv.get().disable_decompress().finish().unwrap();
@ -276,8 +276,8 @@ fn test_body_chunked_implicit() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| { |app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref()))); let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(Body::Streaming(Box::new(body)))})); .body(Body::Streaming(Box::new(body)))}));
let request = srv.get().disable_decompress().finish().unwrap(); let request = srv.get().disable_decompress().finish().unwrap();
@ -300,8 +300,8 @@ fn test_body_br_streaming() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| { |app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref()))); let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.content_encoding(header::ContentEncoding::Br) .content_encoding(http::ContentEncoding::Br)
.body(Body::Streaming(Box::new(body)))})); .body(Body::Streaming(Box::new(body)))}));
let request = srv.get().disable_decompress().finish().unwrap(); let request = srv.get().disable_decompress().finish().unwrap();
@ -322,7 +322,7 @@ fn test_body_br_streaming() {
fn test_head_empty() { fn test_head_empty() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| { |app| app.handler(|_| {
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.content_length(STR.len() as u64).finish()})); .content_length(STR.len() as u64).finish()}));
let request = srv.head().finish().unwrap(); let request = srv.head().finish().unwrap();
@ -330,7 +330,7 @@ fn test_head_empty() {
assert!(response.status().is_success()); assert!(response.status().is_success());
{ {
let len = response.headers().get(header::http::CONTENT_LENGTH).unwrap(); let len = response.headers().get(http::header::CONTENT_LENGTH).unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
} }
@ -343,8 +343,8 @@ fn test_head_empty() {
fn test_head_binary() { fn test_head_binary() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| { |app| app.handler(|_| {
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.content_length(100).body(STR)})); .content_length(100).body(STR)}));
let request = srv.head().finish().unwrap(); let request = srv.head().finish().unwrap();
@ -352,7 +352,7 @@ fn test_head_binary() {
assert!(response.status().is_success()); assert!(response.status().is_success());
{ {
let len = response.headers().get(header::http::CONTENT_LENGTH).unwrap(); let len = response.headers().get(http::header::CONTENT_LENGTH).unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
} }
@ -365,8 +365,8 @@ fn test_head_binary() {
fn test_head_binary2() { fn test_head_binary2() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| { |app| app.handler(|_| {
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(STR) .body(STR)
})); }));
@ -375,7 +375,7 @@ fn test_head_binary2() {
assert!(response.status().is_success()); assert!(response.status().is_success());
{ {
let len = response.headers().get(header::http::CONTENT_LENGTH).unwrap(); let len = response.headers().get(http::header::CONTENT_LENGTH).unwrap();
assert_eq!(format!("{}", STR.len()), len.to_str().unwrap()); assert_eq!(format!("{}", STR.len()), len.to_str().unwrap());
} }
} }
@ -385,9 +385,9 @@ fn test_body_length() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| { |app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref()))); let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.content_length(STR.len() as u64) .content_length(STR.len() as u64)
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(Body::Streaming(Box::new(body)))})); .body(Body::Streaming(Box::new(body)))}));
let request = srv.get().finish().unwrap(); let request = srv.get().finish().unwrap();
@ -404,9 +404,9 @@ fn test_body_chunked_explicit() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler(|_| { |app| app.handler(|_| {
let body = once(Ok(Bytes::from_static(STR.as_ref()))); let body = once(Ok(Bytes::from_static(STR.as_ref())));
httpcodes::HTTPOk.build() httpcodes::HttpOk.build()
.chunked() .chunked()
.content_encoding(header::ContentEncoding::Gzip) .content_encoding(http::ContentEncoding::Gzip)
.body(Body::Streaming(Box::new(body)))})); .body(Body::Streaming(Box::new(body)))}));
let request = srv.get().disable_decompress().finish().unwrap(); let request = srv.get().disable_decompress().finish().unwrap();
@ -427,9 +427,9 @@ fn test_body_chunked_explicit() {
fn test_body_deflate() { fn test_body_deflate() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler( |app| app.handler(
|_| httpcodes::HTTPOk |_| httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Deflate) .content_encoding(http::ContentEncoding::Deflate)
.body(STR))); .body(STR)));
// client request // client request
@ -452,9 +452,9 @@ fn test_body_deflate() {
fn test_body_brotli() { fn test_body_brotli() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
|app| app.handler( |app| app.handler(
|_| httpcodes::HTTPOk |_| httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Br) .content_encoding(http::ContentEncoding::Br)
.body(STR))); .body(STR)));
// client request // client request
@ -477,9 +477,9 @@ fn test_gzip_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
@ -490,7 +490,7 @@ fn test_gzip_encoding() {
let enc = e.finish().unwrap(); let enc = e.finish().unwrap();
let request = srv.post() let request = srv.post()
.header(header::http::CONTENT_ENCODING, "gzip") .header(http::header::CONTENT_ENCODING, "gzip")
.body(enc.clone()).unwrap(); .body(enc.clone()).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -506,9 +506,9 @@ fn test_gzip_encoding_large() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
@ -519,7 +519,7 @@ fn test_gzip_encoding_large() {
let enc = e.finish().unwrap(); let enc = e.finish().unwrap();
let request = srv.post() let request = srv.post()
.header(header::http::CONTENT_ENCODING, "gzip") .header(http::header::CONTENT_ENCODING, "gzip")
.body(enc.clone()).unwrap(); .body(enc.clone()).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -539,9 +539,9 @@ fn test_reading_gzip_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
@ -552,7 +552,7 @@ fn test_reading_gzip_encoding_large_random() {
let enc = e.finish().unwrap(); let enc = e.finish().unwrap();
let request = srv.post() let request = srv.post()
.header(header::http::CONTENT_ENCODING, "gzip") .header(http::header::CONTENT_ENCODING, "gzip")
.body(enc.clone()).unwrap(); .body(enc.clone()).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -568,9 +568,9 @@ fn test_reading_deflate_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
@ -581,7 +581,7 @@ fn test_reading_deflate_encoding() {
// client request // client request
let request = srv.post() let request = srv.post()
.header(header::http::CONTENT_ENCODING, "deflate") .header(http::header::CONTENT_ENCODING, "deflate")
.body(enc).unwrap(); .body(enc).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -597,9 +597,9 @@ fn test_reading_deflate_encoding_large() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
@ -610,7 +610,7 @@ fn test_reading_deflate_encoding_large() {
// client request // client request
let request = srv.post() let request = srv.post()
.header(header::http::CONTENT_ENCODING, "deflate") .header(http::header::CONTENT_ENCODING, "deflate")
.body(enc).unwrap(); .body(enc).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -630,9 +630,9 @@ fn test_reading_deflate_encoding_large_random() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
@ -643,7 +643,7 @@ fn test_reading_deflate_encoding_large_random() {
// client request // client request
let request = srv.post() let request = srv.post()
.header(header::http::CONTENT_ENCODING, "deflate") .header(http::header::CONTENT_ENCODING, "deflate")
.body(enc).unwrap(); .body(enc).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -660,9 +660,9 @@ fn test_brotli_encoding() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
@ -673,7 +673,7 @@ fn test_brotli_encoding() {
// client request // client request
let request = srv.post() let request = srv.post()
.header(header::http::CONTENT_ENCODING, "br") .header(http::header::CONTENT_ENCODING, "br")
.body(enc).unwrap(); .body(enc).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -690,9 +690,9 @@ fn test_brotli_encoding_large() {
let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| { let mut srv = test::TestServer::new(|app| app.handler(|req: HttpRequest| {
req.body() req.body()
.and_then(|bytes: Bytes| { .and_then(|bytes: Bytes| {
Ok(httpcodes::HTTPOk Ok(httpcodes::HttpOk
.build() .build()
.content_encoding(header::ContentEncoding::Identity) .content_encoding(http::ContentEncoding::Identity)
.body(bytes)) .body(bytes))
}).responder()} }).responder()}
)); ));
@ -703,7 +703,7 @@ fn test_brotli_encoding_large() {
// client request // client request
let request = srv.post() let request = srv.post()
.header(header::http::CONTENT_ENCODING, "br") .header(http::header::CONTENT_ENCODING, "br")
.body(enc).unwrap(); .body(enc).unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
assert!(response.status().is_success()); assert!(response.status().is_success());
@ -716,7 +716,7 @@ fn test_brotli_encoding_large() {
#[test] #[test]
fn test_h2() { fn test_h2() {
let srv = test::TestServer::new(|app| app.handler(|_|{ let srv = test::TestServer::new(|app| app.handler(|_|{
httpcodes::HTTPOk.build().body(STR) httpcodes::HttpOk.build().body(STR)
})); }));
let addr = srv.addr(); let addr = srv.addr();
@ -739,7 +739,7 @@ fn test_h2() {
handle.spawn(h2.map_err(|e| println!("GOT ERR={:?}", e))); handle.spawn(h2.map_err(|e| println!("GOT ERR={:?}", e)));
response.and_then(|response| { response.and_then(|response| {
assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.status(), http::StatusCode::OK);
let (_, body) = response.into_parts(); let (_, body) = response.into_parts();
@ -756,7 +756,7 @@ fn test_h2() {
#[test] #[test]
fn test_application() { fn test_application() {
let mut srv = test::TestServer::with_factory( let mut srv = test::TestServer::with_factory(
|| Application::new().resource("/", |r| r.h(httpcodes::HTTPOk))); || Application::new().resource("/", |r| r.h(httpcodes::HttpOk)));
let request = srv.get().finish().unwrap(); let request = srv.get().finish().unwrap();
let response = srv.execute(request.send()).unwrap(); let response = srv.execute(request.send()).unwrap();
@ -800,7 +800,7 @@ fn test_middlewares() {
move |app| app.middleware(MiddlewareTest{start: Arc::clone(&act_num1), move |app| app.middleware(MiddlewareTest{start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2), response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3)}) finish: Arc::clone(&act_num3)})
.handler(httpcodes::HTTPOk) .handler(httpcodes::HttpOk)
); );
let request = srv.get().finish().unwrap(); let request = srv.get().finish().unwrap();
@ -825,7 +825,7 @@ fn test_resource_middlewares() {
let mut srv = test::TestServer::new( let mut srv = test::TestServer::new(
move |app| app.handler2( move |app| app.handler2(
httpcodes::HTTPOk, httpcodes::HttpOk,
MiddlewareTest{start: Arc::clone(&act_num1), MiddlewareTest{start: Arc::clone(&act_num1),
response: Arc::clone(&act_num2), response: Arc::clone(&act_num2),
finish: Arc::clone(&act_num3)}) finish: Arc::clone(&act_num3)})