1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 16:02:59 +01:00
actix-extras/src/httprequest.rs

524 lines
15 KiB
Rust
Raw Normal View History

//! HTTP Request message related code.
2018-07-04 17:01:27 +02:00
use std::cell::{Ref, RefMut};
2018-06-17 04:54:30 +02:00
use std::collections::HashMap;
2018-05-02 02:19:15 +02:00
use std::net::SocketAddr;
2018-06-25 06:58:04 +02:00
use std::ops::Deref;
2018-05-02 02:19:15 +02:00
use std::rc::Rc;
2018-07-04 17:01:27 +02:00
use std::{fmt, str};
2018-05-02 02:19:15 +02:00
2017-12-08 01:40:29 +01:00
use cookie::Cookie;
2018-04-14 01:02:01 +02:00
use futures_cpupool::CpuPool;
2018-06-16 23:22:08 +02:00
use http::{header, HeaderMap, Method, StatusCode, Uri, Version};
2018-04-14 01:02:01 +02:00
use url::{form_urlencoded, Url};
use body::Body;
2018-07-04 17:01:27 +02:00
use error::{CookieParseError, UrlGenerationError};
2018-06-16 23:22:08 +02:00
use extensions::Extensions;
use handler::FromRequest;
use httpmessage::HttpMessage;
use httpresponse::{HttpResponse, HttpResponseBuilder};
2018-04-14 01:02:01 +02:00
use info::ConnectionInfo;
use param::Params;
use payload::Payload;
2018-07-04 17:01:27 +02:00
use router::{Resource, RouteInfo};
use server::Request;
2017-12-06 02:09:15 +01:00
2018-06-17 04:54:30 +02:00
struct Query(HashMap<String, String>);
2018-05-15 19:09:48 +02:00
struct Cookies(Vec<Cookie<'static>>);
2018-06-25 06:58:04 +02:00
/// An HTTP Request
pub struct HttpRequest<S = ()> {
2018-07-04 18:52:49 +02:00
req: Option<Request>,
2018-06-25 06:58:04 +02:00
state: Rc<S>,
route: RouteInfo,
2017-12-09 13:33:40 +01:00
}
2018-06-25 06:58:04 +02:00
impl<S> HttpMessage for HttpRequest<S> {
type Stream = Payload;
2017-11-27 05:32:12 +01:00
#[inline]
2018-06-25 06:58:04 +02:00
fn headers(&self) -> &HeaderMap {
2018-07-04 18:52:49 +02:00
self.request().headers()
2017-12-15 04:34:31 +01:00
}
2017-12-16 07:49:48 +01:00
#[inline]
2018-06-25 06:58:04 +02:00
fn payload(&self) -> Payload {
2018-07-04 18:52:49 +02:00
if let Some(payload) = self.request().inner.payload.borrow_mut().take() {
2018-06-25 06:58:04 +02:00
payload
} else {
Payload::empty()
}
2018-06-08 04:46:38 +02:00
}
2017-11-27 06:18:38 +01:00
}
2018-06-25 06:58:04 +02:00
impl<S> Deref for HttpRequest<S> {
type Target = Request;
fn deref(&self) -> &Request {
2018-07-04 18:52:49 +02:00
self.request()
}
}
2017-11-27 06:18:38 +01:00
impl<S> HttpRequest<S> {
2018-01-01 02:26:32 +01:00
#[inline]
2018-06-25 06:58:04 +02:00
pub(crate) fn new(req: Request, state: Rc<S>, route: RouteInfo) -> HttpRequest<S> {
HttpRequest {
state,
route,
2018-07-04 18:52:49 +02:00
req: Some(req),
2018-06-25 06:58:04 +02:00
}
2018-01-01 02:26:32 +01:00
}
2017-12-16 07:49:48 +01:00
#[inline]
2018-06-25 06:58:04 +02:00
/// Construct new http request with state.
pub(crate) fn with_state<NS>(&self, state: Rc<NS>) -> HttpRequest<NS> {
HttpRequest {
state,
2018-07-04 18:57:40 +02:00
req: self.req.as_ref().map(|r| r.clone()),
2018-06-25 06:58:04 +02:00
route: self.route.clone(),
}
}
2018-06-18 00:41:41 +02:00
#[inline]
2018-06-25 06:58:04 +02:00
/// Construct new http request with new RouteInfo.
pub(crate) fn with_route_info(&self, route: RouteInfo) -> HttpRequest<S> {
HttpRequest {
route,
2018-07-04 18:57:40 +02:00
req: self.req.as_ref().map(|r| r.clone()),
2018-06-25 06:58:04 +02:00
state: self.state.clone(),
}
2017-11-27 05:32:12 +01:00
}
2018-06-25 06:58:04 +02:00
/// Shared application state
2018-06-18 00:41:41 +02:00
#[inline]
2018-06-25 06:58:04 +02:00
pub fn state(&self) -> &S {
&self.state
2017-12-15 04:34:31 +01:00
}
2017-12-07 01:26:27 +01:00
#[inline]
2018-06-25 06:58:04 +02:00
/// Server request
pub fn request(&self) -> &Request {
2018-07-04 18:52:49 +02:00
self.req.as_ref().unwrap()
2017-11-27 06:18:38 +01:00
}
2018-03-07 23:56:53 +01:00
/// Request extensions
#[inline]
2018-06-25 06:58:04 +02:00
pub fn extensions(&self) -> Ref<Extensions> {
2018-07-04 18:52:49 +02:00
self.request().extensions()
}
2018-05-06 18:07:30 +02:00
/// Mutable reference to a the request's extensions
2018-04-19 04:05:24 +02:00
#[inline]
2018-06-25 06:58:04 +02:00
pub fn extensions_mut(&self) -> RefMut<Extensions> {
2018-07-04 18:52:49 +02:00
self.request().extensions_mut()
2018-04-19 04:05:24 +02:00
}
2018-03-07 23:56:53 +01:00
/// Default `CpuPool`
#[inline]
#[doc(hidden)]
2018-03-08 02:40:13 +01:00
pub fn cpu_pool(&self) -> &CpuPool {
2018-07-04 18:52:49 +02:00
self.request().server_settings().cpu_pool()
2018-03-07 23:56:53 +01:00
}
2018-06-25 06:58:04 +02:00
#[inline]
/// Create http response
pub fn response(&self, status: StatusCode, body: Body) -> HttpResponse {
2018-07-04 18:52:49 +02:00
self.request().server_settings().get_response(status, body)
}
2018-06-25 06:58:04 +02:00
#[inline]
/// Create http response builder
pub fn build_response(&self, status: StatusCode) -> HttpResponseBuilder {
2018-07-04 18:52:49 +02:00
self.request()
.server_settings()
.get_response_builder(status)
2017-12-06 02:09:15 +01:00
}
2017-12-01 04:01:25 +01:00
/// Read the Request Uri.
#[inline]
2018-04-14 01:02:01 +02:00
pub fn uri(&self) -> &Uri {
2018-06-25 06:58:04 +02:00
self.request().inner.url.uri()
2018-04-14 01:02:01 +02:00
}
2017-12-01 04:01:25 +01:00
/// Read the Request method.
#[inline]
2018-04-14 01:02:01 +02:00
pub fn method(&self) -> &Method {
2018-06-25 06:58:04 +02:00
&self.request().inner.method
2018-04-14 01:02:01 +02:00
}
/// Read the Request Version.
2017-11-10 22:26:12 +01:00
#[inline]
pub fn version(&self) -> Version {
2018-06-25 06:58:04 +02:00
self.request().inner.version
2017-12-06 06:38:52 +01:00
}
/// The target path of this Request.
#[inline]
pub fn path(&self) -> &str {
2018-06-25 06:58:04 +02:00
self.request().inner.url.path()
}
2018-06-25 06:58:04 +02:00
/// Get *ConnectionInfo* for the correct request.
#[inline]
pub fn connection_info(&self) -> Ref<ConnectionInfo> {
self.request().connection_info()
2017-11-30 00:07:49 +01:00
}
/// Generate url for named resource
///
/// ```rust
2018-06-02 22:45:29 +02:00
/// # extern crate actix_web;
/// # use actix_web::{App, HttpRequest, HttpResponse, http};
/// #
/// fn index(req: HttpRequest) -> HttpResponse {
/// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate url for "foo" resource
/// HttpResponse::Ok().into()
/// }
///
/// fn main() {
2018-03-31 09:16:55 +02:00
/// let app = App::new()
/// .resource("/test/{one}/{two}/{three}", |r| {
/// r.name("foo"); // <- set resource name, then it could be used in `url_for`
/// r.method(http::Method::GET).f(|_| HttpResponse::Ok());
/// })
/// .finish();
/// }
/// ```
2018-04-14 01:02:01 +02:00
pub fn url_for<U, I>(
2018-05-17 21:20:20 +02:00
&self, name: &str, elements: U,
2018-04-14 01:02:01 +02:00
) -> Result<Url, UrlGenerationError>
where
U: IntoIterator<Item = I>,
I: AsRef<str>,
2017-12-07 01:26:27 +01:00
{
2018-06-25 06:58:04 +02:00
self.route.url_for(&self, name, elements)
2017-12-07 01:26:27 +01:00
}
/// Generate url for named resource
///
/// This method is similar to `HttpRequest::url_for()` but it can be used
/// for urls that do not contain variable parts.
pub fn url_for_static(&self, name: &str) -> Result<Url, UrlGenerationError> {
const NO_PARAMS: [&str; 0] = [];
self.url_for(name, &NO_PARAMS)
}
2018-06-25 06:58:04 +02:00
/// This method returns reference to current `RouteInfo` object.
2017-12-07 01:26:27 +01:00
#[inline]
2018-06-25 06:58:04 +02:00
pub fn route(&self) -> &RouteInfo {
&self.route
2017-12-07 01:26:27 +01:00
}
/// This method returns reference to matched `Resource` object.
#[inline]
pub fn resource(&self) -> Option<&Resource> {
2018-06-25 06:58:04 +02:00
self.route.resource()
}
/// Peer socket address
///
2018-01-15 22:47:25 +01:00
/// Peer address is actual socket address, if proxy is used in front of
/// actix http server, then peer address would be address of this proxy.
///
2018-04-14 01:02:01 +02:00
/// To get client connection information `connection_info()` method should
/// be used.
2017-11-10 22:26:12 +01:00
#[inline]
2018-04-23 00:28:04 +02:00
pub fn peer_addr(&self) -> Option<SocketAddr> {
2018-06-25 06:58:04 +02:00
self.request().inner.addr
}
2018-06-17 04:57:51 +02:00
/// url query parameters.
2018-06-25 06:58:04 +02:00
pub fn query(&self) -> Ref<HashMap<String, String>> {
2018-05-17 21:23:37 +02:00
if self.extensions().get::<Query>().is_none() {
2018-06-17 04:54:30 +02:00
let mut query = HashMap::new();
2017-12-28 04:02:29 +01:00
for (key, val) in form_urlencoded::parse(self.query_string().as_ref()) {
2018-06-17 04:54:30 +02:00
query.insert(key.as_ref().to_string(), val.to_string());
2017-12-28 04:02:29 +01:00
}
2018-06-25 06:58:04 +02:00
self.extensions_mut().insert(Query(query));
}
2018-06-25 06:58:04 +02:00
Ref::map(self.extensions(), |ext| &ext.get::<Query>().unwrap().0)
2017-10-16 18:43:10 +02:00
}
/// The query string in the URL.
///
/// E.g., id=10
#[inline]
pub fn query_string(&self) -> &str {
2017-12-19 20:46:11 +01:00
if let Some(query) = self.uri().query().as_ref() {
2017-12-01 04:01:25 +01:00
query
} else {
""
}
}
2017-12-08 03:00:20 +01:00
/// Load request cookies.
2018-06-25 06:58:04 +02:00
#[inline]
pub fn cookies(&self) -> Result<Ref<Vec<Cookie<'static>>>, CookieParseError> {
if self.extensions().get::<Cookies>().is_none() {
2017-12-08 03:00:20 +01:00
let mut cookies = Vec::new();
2018-06-25 06:58:04 +02:00
for hdr in self.request().inner.headers.get_all(header::COOKIE) {
2018-03-08 00:41:46 +01:00
let s = str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?;
2018-03-08 20:16:54 +01:00
for cookie_str in s.split(';').map(|s| s.trim()) {
if !cookie_str.is_empty() {
cookies.push(Cookie::parse_encoded(cookie_str)?.into_owned());
}
}
2017-12-08 03:00:20 +01:00
}
2018-06-25 06:58:04 +02:00
self.extensions_mut().insert(Cookies(cookies));
2017-12-08 03:00:20 +01:00
}
2018-06-25 06:58:04 +02:00
Ok(Ref::map(self.extensions(), |ext| {
&ext.get::<Cookies>().unwrap().0
}))
2017-12-08 03:00:20 +01:00
}
/// Return request cookie.
2018-06-25 06:58:04 +02:00
#[inline]
pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> {
2017-12-08 03:00:20 +01:00
if let Ok(cookies) = self.cookies() {
2018-06-25 06:58:04 +02:00
for cookie in cookies.iter() {
2017-12-08 03:00:20 +01:00
if cookie.name() == name {
2018-06-25 06:58:04 +02:00
return Some(cookie.to_owned());
2017-11-09 06:01:56 +01:00
}
}
}
2017-12-08 03:00:20 +01:00
None
}
2018-05-15 19:09:48 +02:00
pub(crate) fn set_cookies(&mut self, cookies: Option<Vec<Cookie<'static>>>) {
if let Some(cookies) = cookies {
self.extensions_mut().insert(Cookies(cookies));
}
}
/// Get a reference to the Params object.
2018-03-27 03:18:38 +02:00
///
/// Params is a container for url parameters.
2018-04-17 16:51:06 +02:00
/// A variable segment is specified in the form `{identifier}`,
/// where the identifier can be used later in a request handler to
/// access the matched value for that segment.
#[inline]
pub fn match_info(&self) -> &Params {
2018-06-25 06:58:04 +02:00
&self.route.match_info()
}
/// Check if request requires connection upgrade
pub(crate) fn upgrade(&self) -> bool {
2018-06-25 06:58:04 +02:00
self.request().upgrade()
}
/// Set read buffer capacity
///
/// Default buffer capacity is 32Kb.
pub fn set_read_buffer_capacity(&mut self, cap: usize) {
2018-06-25 06:58:04 +02:00
if let Some(payload) = self.request().inner.payload.borrow_mut().as_mut() {
payload.set_read_buffer_capacity(cap)
}
}
2017-11-27 07:20:28 +01:00
}
2018-07-04 18:52:49 +02:00
impl<S> Drop for HttpRequest<S> {
fn drop(&mut self) {
if let Some(req) = self.req.take() {
req.release();
}
}
}
2017-11-27 06:18:38 +01:00
impl<S> Clone for HttpRequest<S> {
fn clone(&self) -> HttpRequest<S> {
2018-06-25 06:58:04 +02:00
HttpRequest {
2018-07-04 18:57:40 +02:00
req: self.req.as_ref().map(|r| r.clone()),
2018-06-25 06:58:04 +02:00
state: self.state.clone(),
route: self.route.clone(),
}
2017-11-27 05:32:12 +01:00
}
}
impl<S> FromRequest<S> for HttpRequest<S> {
2018-04-04 07:06:18 +02:00
type Config = ();
2018-05-02 02:19:15 +02:00
type Result = Self;
#[inline]
fn from_request(req: &HttpRequest<S>, _: &Self::Config) -> Self::Result {
2018-05-02 02:19:15 +02:00
req.clone()
}
}
2017-11-27 06:18:38 +01:00
impl<S> fmt::Debug for HttpRequest<S> {
2017-10-19 08:43:50 +02:00
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2018-04-12 01:34:01 +02:00
let res = writeln!(
2018-04-14 01:02:01 +02:00
f,
"\nHttpRequest {:?} {}:{}",
2018-06-25 06:58:04 +02:00
self.version(),
self.method(),
2018-04-17 21:55:13 +02:00
self.path()
2018-04-14 01:02:01 +02:00
);
if !self.query_string().is_empty() {
2018-04-09 23:25:30 +02:00
let _ = writeln!(f, " query: ?{:?}", self.query_string());
}
if !self.match_info().is_empty() {
2018-06-25 06:58:04 +02:00
let _ = writeln!(f, " params: {:?}", self.match_info());
2017-10-19 08:43:50 +02:00
}
2018-04-09 23:25:30 +02:00
let _ = writeln!(f, " headers:");
2018-06-25 06:58:04 +02:00
for (key, val) in self.headers().iter() {
2018-04-09 23:25:30 +02:00
let _ = writeln!(f, " {:?}: {:?}", key, val);
}
2017-10-19 08:43:50 +02:00
res
}
}
2017-10-23 23:26:01 +02:00
#[cfg(test)]
mod tests {
use super::*;
use resource::ResourceHandler;
2018-07-04 17:01:27 +02:00
use router::{Resource, Router};
2018-04-14 01:02:01 +02:00
use test::TestRequest;
2017-10-23 23:26:01 +02:00
2017-12-13 20:16:26 +01:00
#[test]
fn test_debug() {
2017-12-27 04:48:02 +01:00
let req = TestRequest::with_header("content-type", "text/plain").finish();
2017-12-13 20:16:26 +01:00
let dbg = format!("{:?}", req);
assert!(dbg.contains("HttpRequest"));
}
#[test]
fn test_no_request_cookies() {
2018-06-25 06:58:04 +02:00
let req = TestRequest::default().finish();
2017-12-13 20:16:26 +01:00
assert!(req.cookies().unwrap().is_empty());
}
#[test]
fn test_request_cookies() {
2018-03-08 00:41:46 +01:00
let req = TestRequest::default()
.header(header::COOKIE, "cookie1=value1")
.header(header::COOKIE, "cookie2=value2")
.finish();
2017-12-13 20:16:26 +01:00
{
let cookies = req.cookies().unwrap();
assert_eq!(cookies.len(), 2);
assert_eq!(cookies[0].name(), "cookie1");
assert_eq!(cookies[0].value(), "value1");
assert_eq!(cookies[1].name(), "cookie2");
assert_eq!(cookies[1].value(), "value2");
}
let cookie = req.cookie("cookie1");
assert!(cookie.is_some());
let cookie = cookie.unwrap();
assert_eq!(cookie.name(), "cookie1");
assert_eq!(cookie.value(), "value1");
let cookie = req.cookie("cookie-unknown");
assert!(cookie.is_none());
}
#[test]
fn test_request_query() {
2018-01-03 19:57:57 +01:00
let req = TestRequest::with_uri("/?id=test").finish();
2017-12-13 20:16:26 +01:00
assert_eq!(req.query_string(), "id=test");
let query = req.query();
assert_eq!(&query["id"], "test");
}
#[test]
fn test_request_match_info() {
let mut resource = ResourceHandler::<()>::default();
2017-12-13 20:16:26 +01:00
resource.name("index");
2018-02-22 14:48:18 +01:00
let mut routes = Vec::new();
routes.push((Resource::new("index", "/{key}/"), Some(resource)));
2018-06-25 06:58:04 +02:00
let (router, _) = Router::new("", routes);
2017-12-13 20:16:26 +01:00
2018-06-25 06:58:04 +02:00
let req = TestRequest::with_uri("/value/?id=test").finish();
let info = router.recognize(&req).unwrap().1;
assert_eq!(info.match_info().get("key"), Some("value"));
2017-12-13 20:16:26 +01:00
}
2017-12-07 01:26:27 +01:00
#[test]
fn test_url_for() {
let mut resource = ResourceHandler::<()>::default();
2017-12-07 01:26:27 +01:00
resource.name("index");
let routes =
vec![(Resource::new("index", "/user/{name}.{ext}"), Some(resource))];
2018-06-25 06:58:04 +02:00
let (router, _) = Router::new("/", routes);
2018-07-04 17:01:27 +02:00
let info = router.default_route_info();
2018-06-25 06:58:04 +02:00
assert!(info.has_route("/user/test.html"));
assert!(!info.has_route("/test/unknown"));
2017-12-07 01:26:27 +01:00
2018-03-07 23:56:53 +01:00
let req = TestRequest::with_header(header::HOST, "www.rust-lang.org")
.finish_with_router(router);
2017-12-07 01:26:27 +01:00
2018-04-14 01:02:01 +02:00
assert_eq!(
req.url_for("unknown", &["test"]),
Err(UrlGenerationError::ResourceNotFound)
);
assert_eq!(
req.url_for("index", &["test"]),
Err(UrlGenerationError::NotEnoughElements)
);
2017-12-07 01:26:27 +01:00
let url = req.url_for("index", &["test", "html"]);
2018-04-14 01:02:01 +02:00
assert_eq!(
url.ok().unwrap().as_str(),
"http://www.rust-lang.org/user/test.html"
);
2017-12-07 01:26:27 +01:00
}
#[test]
fn test_url_for_with_prefix() {
let mut resource = ResourceHandler::<()>::default();
resource.name("index");
let routes = vec![(Resource::new("index", "/user/{name}.html"), Some(resource))];
2018-06-25 06:58:04 +02:00
let (router, _) = Router::new("/prefix/", routes);
2018-07-04 17:01:27 +02:00
let info = router.default_route_info();
2018-06-25 06:58:04 +02:00
assert!(info.has_route("/user/test.html"));
assert!(!info.has_route("/prefix/user/test.html"));
2018-06-25 06:58:04 +02:00
let req = TestRequest::with_header(header::HOST, "www.rust-lang.org")
.finish_with_router(router);
let url = req.url_for("index", &["test"]);
2018-04-14 01:02:01 +02:00
assert_eq!(
url.ok().unwrap().as_str(),
"http://www.rust-lang.org/prefix/user/test.html"
);
}
#[test]
fn test_url_for_static() {
let mut resource = ResourceHandler::<()>::default();
resource.name("index");
let routes = vec![(Resource::new("index", "/index.html"), Some(resource))];
2018-06-25 06:58:04 +02:00
let (router, _) = Router::new("/prefix/", routes);
2018-07-04 17:01:27 +02:00
let info = router.default_route_info();
2018-06-25 06:58:04 +02:00
assert!(info.has_route("/index.html"));
assert!(!info.has_route("/prefix/index.html"));
2018-06-25 06:58:04 +02:00
let req = TestRequest::default()
.header(header::HOST, "www.rust-lang.org")
.finish_with_router(router);
let url = req.url_for_static("index");
assert_eq!(
url.ok().unwrap().as_str(),
"http://www.rust-lang.org/prefix/index.html"
);
}
#[test]
fn test_url_for_external() {
let mut resource = ResourceHandler::<()>::default();
resource.name("index");
2018-04-29 07:55:47 +02:00
let routes = vec![(
2018-05-07 19:53:45 +02:00
Resource::external("youtube", "https://youtube.com/watch/{video_id}"),
None,
2018-04-29 07:55:47 +02:00
)];
2018-06-25 06:58:04 +02:00
let router = Router::new::<()>("", routes).0;
2018-07-04 17:01:27 +02:00
let info = router.default_route_info();
2018-06-25 06:58:04 +02:00
assert!(!info.has_route("https://youtube.com/watch/unknown"));
2018-06-25 06:58:04 +02:00
let req = TestRequest::default().finish_with_router(router);
let url = req.url_for("youtube", &["oHg5SJYRHA0"]);
2018-04-29 18:09:08 +02:00
assert_eq!(
url.ok().unwrap().as_str(),
"https://youtube.com/watch/oHg5SJYRHA0"
);
}
2017-10-23 23:26:01 +02:00
}