1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-10-11 04:32:28 +00:00
actix-web/src/httpmessage.rs

363 lines
9.4 KiB
Rust
Raw Normal View History

2017-10-07 04:48:14 +00:00
//! Pieces pertaining to the HTTP message protocol.
use std::{io, mem};
use std::convert::Into;
use bytes::Bytes;
2017-10-10 06:07:32 +00:00
use http::{Method, StatusCode, Version, Uri, HeaderMap};
use http::header::{self, HeaderName, HeaderValue};
2017-10-07 04:48:14 +00:00
use Params;
use error::Error;
2017-10-08 04:48:00 +00:00
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum ConnectionType {
Close,
KeepAlive,
Upgrade,
}
2017-10-07 04:48:14 +00:00
pub trait Message {
fn version(&self) -> Version;
2017-10-10 06:07:32 +00:00
fn headers(&self) -> &HeaderMap;
2017-10-07 04:48:14 +00:00
/// Checks if a connection should be kept alive.
2017-10-10 06:07:32 +00:00
fn keep_alive(&self) -> bool {
if let Some(conn) = self.headers().get(header::CONNECTION) {
if let Ok(conn) = conn.to_str() {
if self.version() == Version::HTTP_10 && !conn.contains("keep-alive") {
false
} else if self.version() == Version::HTTP_11 && conn.contains("close") {
false
} else {
true
}
} else {
false
}
} else {
self.version() != Version::HTTP_10
}
2017-10-07 04:48:14 +00:00
}
/// Checks if a connection is expecting a `100 Continue` before sending its body.
#[inline]
fn expecting_continue(&self) -> bool {
2017-10-10 06:07:32 +00:00
if self.version() == Version::HTTP_11 {
if let Some(hdr) = self.headers().get(header::EXPECT) {
if let Ok(hdr) = hdr.to_str() {
return hdr.to_lowercase().contains("continue")
}
}
}
false
2017-10-07 04:48:14 +00:00
}
fn is_chunked(&self) -> Result<bool, Error> {
2017-10-10 06:07:32 +00:00
if let Some(encodings) = self.headers().get(header::TRANSFER_ENCODING) {
if let Ok(s) = encodings.to_str() {
return Ok(s.to_lowercase().contains("chunked"))
2017-10-07 04:48:14 +00:00
} else {
debug!("request with transfer-encoding header, but not chunked, bad request");
Err(Error::Header)
}
} else {
Ok(false)
}
}
}
#[derive(Debug)]
/// An HTTP Request
pub struct HttpRequest {
version: Version,
method: Method,
uri: Uri,
2017-10-10 06:07:32 +00:00
headers: HeaderMap,
2017-10-07 04:48:14 +00:00
params: Params,
}
impl Message for HttpRequest {
fn version(&self) -> Version {
self.version
}
2017-10-10 06:07:32 +00:00
fn headers(&self) -> &HeaderMap {
2017-10-07 04:48:14 +00:00
&self.headers
}
}
impl HttpRequest {
/// Construct a new Request.
#[inline]
2017-10-10 06:07:32 +00:00
pub fn new(method: Method, uri: Uri, version: Version, headers: HeaderMap) -> Self {
2017-10-07 04:48:14 +00:00
HttpRequest {
method: method,
uri: uri,
version: version,
headers: headers,
params: Params::new(),
}
}
/// Read the Request Uri.
#[inline]
pub fn uri(&self) -> &Uri { &self.uri }
/// Read the Request Version.
#[inline]
pub fn version(&self) -> Version { self.version }
/// Read the Request headers.
#[inline]
2017-10-10 06:07:32 +00:00
pub fn headers(&self) -> &HeaderMap { &self.headers }
2017-10-07 04:48:14 +00:00
/// Read the Request method.
#[inline]
pub fn method(&self) -> &Method { &self.method }
// /// The remote socket address of this request
// ///
// /// This is an `Option`, because some underlying transports may not have
// /// a socket address, such as Unix Sockets.
// ///
// /// This field is not used for outgoing requests.
// #[inline]
// pub fn remote_addr(&self) -> Option<SocketAddr> { self.remote_addr }
/// The target path of this Request.
#[inline]
pub fn path(&self) -> &str {
self.uri.path()
}
/// The query string of this Request.
#[inline]
pub fn query(&self) -> Option<&str> {
self.uri.query()
}
/// Get a mutable reference to the Request headers.
#[inline]
2017-10-10 06:07:32 +00:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
2017-10-07 04:48:14 +00:00
&mut self.headers
}
2017-10-08 06:59:57 +00:00
/// Get a reference to the Params object.
/// Params is a container for url parameters.
/// Route supports glob patterns: * for a single wildcard segment and :param
/// for matching storing that segment of the request url in the Params object.
2017-10-07 04:48:14 +00:00
#[inline]
pub fn params(&self) -> &Params { &self.params }
2017-10-08 06:59:57 +00:00
/// Create new request with Params object.
2017-10-07 04:48:14 +00:00
pub fn with_params(self, params: Params) -> Self {
HttpRequest {
method: self.method,
uri: self.uri,
version: self.version,
headers: self.headers,
params: params
}
}
2017-10-08 04:48:00 +00:00
2017-10-08 06:59:57 +00:00
pub(crate) fn is_upgrade(&self) -> bool {
2017-10-10 06:07:32 +00:00
if let Some(ref conn) = self.headers().get(header::CONNECTION) {
if let Ok(s) = conn.to_str() {
return s.to_lowercase().contains("upgrade")
}
2017-10-08 04:48:00 +00:00
}
2017-10-10 06:07:32 +00:00
false
2017-10-08 04:48:00 +00:00
}
2017-10-07 04:48:14 +00:00
}
2017-10-07 06:14:13 +00:00
/// Represents various types of http message body.
2017-10-07 04:48:14 +00:00
#[derive(Debug)]
pub enum Body {
2017-10-07 06:14:13 +00:00
/// Empty response. `Content-Length` header is set to `0`
2017-10-07 04:48:14 +00:00
Empty,
2017-10-07 06:14:13 +00:00
/// Specific response body. `Content-Length` header is set to length of bytes.
2017-10-07 04:48:14 +00:00
Binary(Bytes),
2017-10-07 06:14:13 +00:00
/// Streaming response body with specified length.
2017-10-07 04:48:14 +00:00
Length(u64),
2017-10-07 06:14:13 +00:00
/// Unspecified streaming response. Developer is responsible for setting
/// right `Content-Length` or `Transfer-Encoding` headers.
2017-10-07 04:48:14 +00:00
Streaming,
2017-10-08 04:48:00 +00:00
/// Upgrade connection.
Upgrade,
2017-10-07 04:48:14 +00:00
}
impl Body {
2017-10-07 06:14:13 +00:00
/// Does this body have payload.
2017-10-07 04:48:14 +00:00
pub fn has_body(&self) -> bool {
match *self {
Body::Length(_) | Body::Streaming => true,
_ => false
}
}
}
2017-10-08 21:56:51 +00:00
/// Implements by something that can be converted to `HttpResponse`
2017-10-07 06:14:13 +00:00
pub trait IntoHttpResponse {
/// Convert into response.
2017-10-08 04:48:00 +00:00
fn response(self, req: HttpRequest) -> HttpResponse;
2017-10-07 04:48:14 +00:00
}
#[derive(Debug)]
/// An HTTP Response
2017-10-07 06:14:13 +00:00
pub struct HttpResponse {
2017-10-07 04:48:14 +00:00
request: HttpRequest,
pub version: Version,
2017-10-10 06:07:32 +00:00
pub headers: HeaderMap,
2017-10-07 04:48:14 +00:00
pub status: StatusCode,
2017-10-08 04:48:00 +00:00
reason: Option<&'static str>,
2017-10-07 04:48:14 +00:00
body: Body,
chunked: bool,
2017-10-10 06:07:32 +00:00
// compression: Option<Encoding>,
2017-10-08 04:48:00 +00:00
connection_type: Option<ConnectionType>,
2017-10-07 04:48:14 +00:00
}
2017-10-07 06:14:13 +00:00
impl Message for HttpResponse {
2017-10-07 04:48:14 +00:00
fn version(&self) -> Version {
self.version
}
2017-10-10 06:07:32 +00:00
fn headers(&self) -> &HeaderMap {
2017-10-07 04:48:14 +00:00
&self.headers
}
}
2017-10-07 06:14:13 +00:00
impl HttpResponse {
/// Constructs a response
2017-10-07 04:48:14 +00:00
#[inline]
2017-10-07 06:14:13 +00:00
pub fn new(request: HttpRequest, status: StatusCode, body: Body) -> HttpResponse {
2017-10-07 04:48:14 +00:00
let version = request.version;
2017-10-07 06:14:13 +00:00
HttpResponse {
2017-10-07 04:48:14 +00:00
request: request,
version: version,
headers: Default::default(),
status: status,
2017-10-08 04:48:00 +00:00
reason: None,
2017-10-07 04:48:14 +00:00
body: body,
chunked: false,
2017-10-10 06:07:32 +00:00
// compression: None,
2017-10-08 04:48:00 +00:00
connection_type: None,
2017-10-07 04:48:14 +00:00
}
}
2017-10-08 04:48:00 +00:00
/// Original prequest
#[inline]
pub fn request(&self) -> &HttpRequest {
&self.request
}
2017-10-07 04:48:14 +00:00
/// Get the HTTP version of this response.
#[inline]
pub fn version(&self) -> Version {
self.version
}
/// Get the headers from the response.
#[inline]
2017-10-10 06:07:32 +00:00
pub fn headers(&self) -> &HeaderMap {
2017-10-07 04:48:14 +00:00
&self.headers
}
/// Get a mutable reference to the headers.
#[inline]
2017-10-10 06:07:32 +00:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
2017-10-07 04:48:14 +00:00
&mut self.headers
}
/// Get the status from the server.
#[inline]
pub fn status(&self) -> StatusCode {
self.status
}
/// Set the `StatusCode` for this response.
#[inline]
2017-10-08 04:48:00 +00:00
pub fn set_status(mut self, status: StatusCode) -> Self {
2017-10-07 04:48:14 +00:00
self.status = status;
self
}
/// Set a header and move the Response.
#[inline]
2017-10-10 06:07:32 +00:00
pub fn set_header(mut self, name: HeaderName, value: HeaderValue) -> Self {
self.headers.insert(name, value);
2017-10-07 04:48:14 +00:00
self
}
2017-10-08 04:48:00 +00:00
/// Set the headers.
2017-10-07 04:48:14 +00:00
#[inline]
2017-10-10 06:07:32 +00:00
pub fn with_headers(mut self, headers: HeaderMap) -> Self {
2017-10-07 04:48:14 +00:00
self.headers = headers;
self
}
2017-10-08 04:48:00 +00:00
/// Set the custom reason for the response.
#[inline]
pub fn set_reason(mut self, reason: &'static str) -> Self {
self.reason = Some(reason);
self
}
/// Set connection type
pub fn set_connection_type(mut self, conn: ConnectionType) -> Self {
self.connection_type = Some(conn);
self
}
/// Connection upgrade status
pub fn upgrade(&self) -> bool {
self.connection_type == Some(ConnectionType::Upgrade)
}
2017-10-07 04:48:14 +00:00
/// Keep-alive status for this connection
pub fn keep_alive(&self) -> bool {
2017-10-08 04:48:00 +00:00
if let Some(ConnectionType::KeepAlive) = self.connection_type {
true
2017-10-07 04:48:14 +00:00
} else {
2017-10-10 06:07:32 +00:00
self.request.keep_alive()
2017-10-07 04:48:14 +00:00
}
}
2017-10-08 04:48:00 +00:00
2017-10-07 04:48:14 +00:00
/// Force close connection, even if it is marked as keep-alive
pub fn force_close(&mut self) {
2017-10-08 04:48:00 +00:00
self.connection_type = Some(ConnectionType::Close);
2017-10-07 04:48:14 +00:00
}
/// is chunked encoding enabled
pub fn chunked(&self) -> bool {
self.chunked
}
/// Enables automatic chunked transfer encoding
pub fn enable_chunked_encoding(&mut self) -> Result<(), io::Error> {
2017-10-10 06:07:32 +00:00
if self.headers.contains_key(header::CONTENT_LENGTH) {
2017-10-07 04:48:14 +00:00
Err(io::Error::new(io::ErrorKind::Other,
"You can't enable chunked encoding when a content length is set"))
} else {
self.chunked = true;
Ok(())
}
}
2017-10-07 06:14:13 +00:00
/// Get body os this response
2017-10-07 04:48:14 +00:00
pub fn body(&self) -> &Body {
&self.body
}
2017-10-08 04:48:00 +00:00
/// Set a body
pub fn set_body<B: Into<Body>>(mut self, body: B) -> Self {
self.body = body.into();
self
}
2017-10-07 06:14:13 +00:00
/// Set a body and return previous body value
2017-10-08 04:48:00 +00:00
pub fn replace_body<B: Into<Body>>(&mut self, body: B) -> Body {
2017-10-07 04:48:14 +00:00
mem::replace(&mut self.body, body.into())
}
}