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

708 lines
22 KiB
Rust
Raw Normal View History

//! HTTP Request message related code.
use std::{io, cmp, str, fmt, mem};
2017-11-27 05:32:12 +01:00
use std::rc::Rc;
use std::net::SocketAddr;
use std::borrow::Cow;
use bytes::Bytes;
2017-12-08 01:40:29 +01:00
use cookie::Cookie;
2018-03-29 18:26:01 +02:00
use futures::{Async, Stream, Poll};
use futures::future::{FutureResult, result};
2018-03-07 23:56:53 +01:00
use futures_cpupool::CpuPool;
use failure;
2017-12-09 22:25:06 +01:00
use url::{Url, form_urlencoded};
use http::{header, Uri, Method, Version, HeaderMap, Extensions, StatusCode};
use tokio_io::AsyncRead;
use percent_encoding::percent_decode;
use body::Body;
2017-12-06 02:09:15 +01:00
use info::ConnectionInfo;
use param::Params;
use router::{Router, Resource};
2018-02-25 09:21:45 +01:00
use payload::Payload;
use handler::FromRequest;
use httpmessage::HttpMessage;
use httpresponse::{HttpResponse, HttpResponseBuilder};
use server::helpers::SharedHttpInnerMessage;
use error::{Error, UrlGenerationError, CookieParseError, PayloadError};
2017-12-06 02:09:15 +01:00
pub struct HttpInnerMessage {
2017-12-09 13:33:40 +01:00
pub version: Version,
pub method: Method,
pub uri: Uri,
pub headers: HeaderMap,
pub extensions: Extensions,
pub params: Params<'static>,
pub cookies: Option<Vec<Cookie<'static>>>,
2017-12-28 04:02:29 +01:00
pub query: Params<'static>,
pub query_loaded: bool,
2017-12-09 13:33:40 +01:00
pub addr: Option<SocketAddr>,
2017-12-13 06:32:58 +01:00
pub payload: Option<Payload>,
2017-12-09 13:33:40 +01:00
pub info: Option<ConnectionInfo<'static>>,
resource: RouterResource,
}
#[derive(Debug, Copy, Clone,PartialEq)]
enum RouterResource {
Notset,
Normal(u16),
}
impl Default for HttpInnerMessage {
fn default() -> HttpInnerMessage {
HttpInnerMessage {
method: Method::GET,
2017-12-01 04:01:25 +01:00
uri: Uri::default(),
version: Version::HTTP_11,
2017-12-16 07:49:48 +01:00
headers: HeaderMap::with_capacity(16),
2017-12-28 04:19:28 +01:00
params: Params::new(),
query: Params::new(),
2017-12-28 04:02:29 +01:00
query_loaded: false,
2017-12-08 03:00:20 +01:00
cookies: None,
addr: None,
2017-12-13 06:32:58 +01:00
payload: None,
2017-11-27 05:32:12 +01:00
extensions: Extensions::new(),
2017-12-06 02:09:15 +01:00
info: None,
resource: RouterResource::Notset,
}
}
2017-11-27 05:32:12 +01:00
}
impl HttpInnerMessage {
2017-12-09 13:33:40 +01:00
/// Checks if a connection should be kept alive.
2017-12-16 07:49:48 +01:00
#[inline]
2017-12-09 13:33:40 +01:00
pub 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") {
true
} else {
self.version == Version::HTTP_11 &&
!(conn.contains("close") || conn.contains("upgrade"))
}
} else {
false
}
} else {
self.version != Version::HTTP_10
}
}
2017-12-15 04:34:31 +01:00
2017-12-16 07:49:48 +01:00
#[inline]
2017-12-15 04:34:31 +01:00
pub(crate) fn reset(&mut self) {
self.headers.clear();
self.extensions.clear();
self.params.clear();
2017-12-28 04:02:29 +01:00
self.query.clear();
self.query_loaded = false;
2017-12-16 07:49:48 +01:00
self.cookies = None;
self.addr = None;
self.info = None;
2017-12-19 09:18:57 +01:00
self.payload = None;
self.resource = RouterResource::Notset;
2017-12-15 04:34:31 +01:00
}
2017-12-09 13:33:40 +01:00
}
lazy_static!{
static ref RESOURCE: Resource = Resource::unset();
}
2017-11-27 05:32:12 +01:00
/// An HTTP Request
pub struct HttpRequest<S=()>(SharedHttpInnerMessage, Option<Rc<S>>, Option<Router>);
2017-11-27 05:32:12 +01:00
2017-11-27 06:18:38 +01:00
impl HttpRequest<()> {
2017-11-27 05:32:12 +01:00
/// Construct a new Request.
#[inline]
2017-12-01 04:01:25 +01:00
pub fn new(method: Method, uri: Uri,
2018-03-09 19:00:15 +01:00
version: Version, headers: HeaderMap, payload: Option<Payload>)
-> HttpRequest
2017-11-27 05:32:12 +01:00
{
HttpRequest(
SharedHttpInnerMessage::from_message(HttpInnerMessage {
2018-02-26 23:33:56 +01:00
method,
uri,
version,
headers,
payload,
2017-12-28 04:19:28 +01:00
params: Params::new(),
query: Params::new(),
2017-12-28 04:02:29 +01:00
query_loaded: false,
2017-12-08 03:00:20 +01:00
cookies: None,
2017-11-27 05:32:12 +01:00
addr: None,
extensions: Extensions::new(),
2017-12-06 02:09:15 +01:00
info: None,
resource: RouterResource::Notset,
2017-12-09 22:25:06 +01:00
}),
2017-12-13 06:32:58 +01:00
None,
2017-12-09 22:25:06 +01:00
None,
)
}
2017-12-16 07:49:48 +01:00
#[inline(always)]
2018-03-09 19:11:38 +01:00
#[cfg_attr(feature="cargo-clippy", allow(inline_always))]
pub(crate) fn from_message(msg: SharedHttpInnerMessage) -> HttpRequest {
2017-12-15 04:34:31 +01:00
HttpRequest(msg, None, None)
}
2017-12-16 07:49:48 +01:00
#[inline]
2017-11-27 06:18:38 +01:00
/// Construct new http request with state.
2017-12-26 18:00:45 +01:00
pub fn with_state<S>(self, state: Rc<S>, router: Router) -> HttpRequest<S> {
2017-12-13 06:32:58 +01:00
HttpRequest(self.0, Some(state), Some(router))
2017-11-27 06:18:38 +01:00
}
}
impl<S> HttpMessage for HttpRequest<S> {
#[inline]
fn headers(&self) -> &HeaderMap {
&self.as_ref().headers
}
}
2017-11-27 06:18:38 +01:00
impl<S> HttpRequest<S> {
2018-01-01 02:26:32 +01:00
#[inline]
/// Construct new http request with state.
pub fn change_state<NS>(&self, state: Rc<NS>) -> HttpRequest<NS> {
HttpRequest(self.0.clone(), Some(state), self.2.clone())
2018-01-01 02:26:32 +01:00
}
2017-12-16 07:49:48 +01:00
#[inline]
/// Construct new http request without state.
2018-02-26 23:33:56 +01:00
pub(crate) fn without_state(&self) -> HttpRequest {
2018-03-07 23:56:53 +01:00
HttpRequest(self.0.clone(), None, self.2.clone())
}
/// get mutable reference for inner message
/// mutable reference should not be returned as result for request's method
2017-12-16 07:49:48 +01:00
#[inline(always)]
#[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref, inline_always))]
pub(crate) fn as_mut(&self) -> &mut HttpInnerMessage {
2017-12-15 04:34:31 +01:00
self.0.get_mut()
2017-11-27 05:32:12 +01:00
}
2017-12-16 07:49:48 +01:00
#[inline(always)]
#[cfg_attr(feature = "cargo-clippy", allow(mut_from_ref, inline_always))]
fn as_ref(&self) -> &HttpInnerMessage {
2017-12-15 04:34:31 +01:00
self.0.get_ref()
}
#[inline]
pub(crate) fn get_inner(&mut self) -> &mut HttpInnerMessage {
2017-12-09 13:33:40 +01:00
self.as_mut()
}
2017-11-27 06:18:38 +01:00
/// Shared application state
2017-12-07 01:26:27 +01:00
#[inline]
2017-11-27 06:18:38 +01:00
pub fn state(&self) -> &S {
2017-12-13 06:32:58 +01:00
self.1.as_ref().unwrap()
2017-11-27 06:18:38 +01:00
}
2018-03-07 23:56:53 +01:00
/// Request extensions
#[inline]
pub fn extensions(&mut self) -> &mut Extensions {
2017-11-27 05:32:12 +01:00
&mut self.as_mut().extensions
}
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-03-07 23:56:53 +01:00
self.router().expect("HttpRequest has to have Router instance")
.server_settings().cpu_pool()
}
/// Create http response
pub fn response(&self, status: StatusCode, body: Body) -> HttpResponse {
if let Some(router) = self.router() {
router.server_settings().get_response(status, body)
} else {
HttpResponse::with_body(status, body)
}
}
/// Create http response builder
pub fn build_response(&self, status: StatusCode) -> HttpResponseBuilder {
if let Some(router) = self.router() {
router.server_settings().get_response_builder(status)
} else {
HttpResponse::build(status)
}
}
2017-12-06 02:09:15 +01:00
#[doc(hidden)]
pub fn prefix_len(&self) -> usize {
2017-12-16 07:49:48 +01:00
if let Some(router) = self.router() { router.prefix().len() } else { 0 }
2017-12-06 02:09:15 +01:00
}
2017-12-01 04:01:25 +01:00
/// Read the Request Uri.
#[inline]
2017-12-15 04:34:31 +01:00
pub fn uri(&self) -> &Uri { &self.as_ref().uri }
2017-12-01 04:01:25 +01:00
2018-03-17 16:10:22 +01:00
/// Returns mutable the Request Uri.
///
2018-03-17 16:10:22 +01:00
/// This might be useful for middlewares, e.g. path normalization.
#[inline]
pub fn uri_mut(&mut self) -> &mut Uri {
&mut self.as_mut().uri
}
/// Read the Request method.
#[inline]
2017-12-15 04:34:31 +01:00
pub fn method(&self) -> &Method { &self.as_ref().method }
/// Read the Request Version.
2017-11-10 22:26:12 +01:00
#[inline]
pub fn version(&self) -> Version {
2017-12-15 04:34:31 +01:00
self.as_ref().version
}
2018-03-17 16:10:22 +01:00
///Returns mutable Request's headers.
///
///This is intended to be used by middleware.
2017-12-08 18:24:05 +01:00
#[inline]
2017-12-06 06:38:52 +01:00
pub fn headers_mut(&mut self) -> &mut HeaderMap {
&mut self.as_mut().headers
}
/// The target path of this Request.
#[inline]
pub fn path(&self) -> &str {
2017-12-19 20:46:11 +01:00
self.uri().path()
}
/// Percent decoded path of this Request.
#[inline]
pub fn path_decoded(&self) -> Cow<str> {
percent_decode(self.uri().path().as_bytes()).decode_utf8().unwrap()
}
2018-01-15 22:47:25 +01:00
/// Get *ConnectionInfo* for correct request.
2017-12-08 02:38:18 +01:00
pub fn connection_info(&self) -> &ConnectionInfo {
2017-12-15 04:34:31 +01:00
if self.as_ref().info.is_none() {
2017-12-06 02:09:15 +01:00
let info: ConnectionInfo<'static> = unsafe{
mem::transmute(ConnectionInfo::new(self))};
self.as_mut().info = Some(info);
}
2017-12-15 04:34:31 +01:00
self.as_ref().info.as_ref().unwrap()
2017-11-30 00:07:49 +01:00
}
/// Generate url for named resource
///
/// ```rust
/// # extern crate actix_web;
2018-03-31 09:16:55 +02:00
/// # 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();
/// }
/// ```
2017-12-08 02:38:18 +01:00
pub fn url_for<U, I>(&self, name: &str, elements: U) -> Result<Url, UrlGenerationError>
2017-12-07 01:26:27 +01:00
where U: IntoIterator<Item=I>,
I: AsRef<str>,
{
if self.router().is_none() {
Err(UrlGenerationError::RouterNotAvailable)
} else {
let path = self.router().unwrap().resource_path(name, elements)?;
if path.starts_with('/') {
2017-12-08 02:38:18 +01:00
let conn = self.connection_info();
Ok(Url::parse(&format!("{}://{}{}", conn.scheme(), conn.host(), path))?)
} else {
Ok(Url::parse(&path)?)
}
2017-12-07 01:26:27 +01:00
}
}
/// This method returns reference to current `Router` object.
2017-12-07 01:26:27 +01:00
#[inline]
2017-12-26 18:00:45 +01:00
pub fn router(&self) -> Option<&Router> {
2017-12-07 01:26:27 +01:00
self.2.as_ref()
}
/// This method returns reference to matched `Resource` object.
#[inline]
pub fn resource(&self) -> &Resource {
if let Some(ref router) = self.2 {
if let RouterResource::Normal(idx) = self.as_ref().resource {
return router.get_resource(idx as usize)
}
}
&*RESOURCE
}
pub(crate) fn set_resource(&mut self, res: usize) {
self.as_mut().resource = RouterResource::Normal(res as u16);
}
/// 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.
///
/// To get client connection information `connection_info()` method should be used.
2017-11-10 22:26:12 +01:00
#[inline]
2017-12-06 06:38:52 +01:00
pub fn peer_addr(&self) -> Option<&SocketAddr> {
2017-12-15 04:34:31 +01:00
self.as_ref().addr.as_ref()
}
2017-12-07 01:26:27 +01:00
#[inline]
2017-12-06 06:38:52 +01:00
pub(crate) fn set_peer_addr(&mut self, addr: Option<SocketAddr>) {
2017-11-27 05:32:12 +01:00
self.as_mut().addr = addr
}
2017-12-28 04:02:29 +01:00
/// Get a reference to the Params object.
/// Params is a container for url query parameters.
pub fn query(&self) -> &Params {
if !self.as_ref().query_loaded {
let params: &mut Params = unsafe{ mem::transmute(&mut self.as_mut().query) };
self.as_mut().query_loaded = true;
for (key, val) in form_urlencoded::parse(self.query_string().as_ref()) {
params.add(key, val);
}
}
2017-12-28 04:02:29 +01:00
unsafe{ mem::transmute(&self.as_ref().query) }
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.
pub fn cookies(&self) -> Result<&Vec<Cookie<'static>>, CookieParseError> {
2017-12-15 04:34:31 +01:00
if self.as_ref().cookies.is_none() {
2017-11-27 05:32:12 +01:00
let msg = self.as_mut();
2017-12-08 03:00:20 +01:00
let mut cookies = Vec::new();
2018-03-08 00:41:46 +01:00
for hdr in msg.headers.get_all(header::COOKIE) {
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
}
msg.cookies = Some(cookies)
}
2017-12-15 04:34:31 +01:00
Ok(self.as_ref().cookies.as_ref().unwrap())
2017-12-08 03:00:20 +01:00
}
/// Return request cookie.
pub fn cookie(&self, name: &str) -> Option<&Cookie> {
if let Ok(cookies) = self.cookies() {
for cookie in cookies {
if cookie.name() == name {
return Some(cookie)
2017-11-09 06:01:56 +01:00
}
}
}
2017-12-08 03:00:20 +01:00
None
}
/// Get a reference to the Params object.
2018-03-27 03:18:38 +02:00
///
/// 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.
#[inline]
pub fn match_info(&self) -> &Params {
2017-12-15 04:34:31 +01:00
unsafe{ mem::transmute(&self.as_ref().params) }
}
2017-12-19 20:46:11 +01:00
/// Get mutable reference to request's Params.
2017-12-07 01:26:27 +01:00
#[inline]
pub fn match_info_mut(&mut self) -> &mut Params {
unsafe{ mem::transmute(&mut self.as_mut().params) }
}
/// Checks if a connection should be kept alive.
pub fn keep_alive(&self) -> bool {
2017-12-16 07:49:48 +01:00
self.as_ref().keep_alive()
}
/// Check if request requires connection upgrade
pub(crate) fn upgrade(&self) -> bool {
2017-12-15 04:34:31 +01:00
if let Some(conn) = self.as_ref().headers.get(header::CONNECTION) {
if let Ok(s) = conn.to_str() {
return s.to_lowercase().contains("upgrade")
}
}
2017-12-15 04:34:31 +01:00
self.as_ref().method == Method::CONNECT
}
/// Set read buffer capacity
///
/// Default buffer capacity is 32Kb.
pub fn set_read_buffer_capacity(&mut self, cap: usize) {
if let Some(ref mut payload) = self.as_mut().payload {
payload.set_read_buffer_capacity(cap)
}
}
#[cfg(test)]
pub(crate) fn payload(&self) -> &Payload {
let msg = self.as_mut();
if msg.payload.is_none() {
msg.payload = Some(Payload::empty());
}
msg.payload.as_ref().unwrap()
}
#[cfg(test)]
pub(crate) fn payload_mut(&mut self) -> &mut Payload {
let msg = self.as_mut();
if msg.payload.is_none() {
msg.payload = Some(Payload::empty());
}
msg.payload.as_mut().unwrap()
}
}
2017-11-27 07:20:28 +01:00
impl Default for HttpRequest<()> {
/// Construct default request
fn default() -> HttpRequest {
HttpRequest(SharedHttpInnerMessage::default(), None, None)
2017-11-27 07:20:28 +01:00
}
}
2017-11-27 06:18:38 +01:00
impl<S> Clone for HttpRequest<S> {
fn clone(&self) -> HttpRequest<S> {
2018-02-19 23:26:51 +01:00
HttpRequest(self.0.clone(), self.1.clone(), self.2.clone())
2017-11-27 05:32:12 +01:00
}
}
impl<S: 'static> FromRequest<S> for HttpRequest<S>
{
2018-04-04 07:06:18 +02:00
type Config = ();
type Result = FutureResult<Self, Error>;
#[inline]
2018-04-04 07:06:18 +02:00
fn from_request(req: &HttpRequest<S>, _: &Self::Config) -> Self::Result {
result(Ok(req.clone()))
}
}
2018-02-25 09:21:45 +01:00
impl<S> Stream for HttpRequest<S> {
type Item = Bytes;
type Error = PayloadError;
fn poll(&mut self) -> Poll<Option<Bytes>, PayloadError> {
let msg = self.as_mut();
if msg.payload.is_none() {
Ok(Async::Ready(None))
} else {
msg.payload.as_mut().unwrap().poll()
}
2018-02-25 09:21:45 +01:00
}
}
impl<S> io::Read for HttpRequest<S> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.as_mut().payload.is_some() {
match self.as_mut().payload.as_mut().unwrap().poll() {
Ok(Async::Ready(Some(mut b))) => {
let i = cmp::min(b.len(), buf.len());
buf.copy_from_slice(&b.split_to(i)[..i]);
if !b.is_empty() {
self.as_mut().payload.as_mut().unwrap().unread_data(b);
}
if i < buf.len() {
match self.read(&mut buf[i..]) {
Ok(n) => Ok(i + n),
Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => Ok(i),
Err(e) => Err(e),
}
} else {
Ok(i)
}
}
Ok(Async::Ready(None)) => Ok(0),
Ok(Async::NotReady) =>
Err(io::Error::new(io::ErrorKind::WouldBlock, "Not ready")),
Err(e) =>
Err(io::Error::new(io::ErrorKind::Other, failure::Error::from(e).compat())),
}
} else {
Ok(0)
}
}
}
impl<S> AsyncRead for HttpRequest<S> {}
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-09 23:25:30 +02:00
let res = writeln!(f, "\nHttpRequest {:?} {}:{}",
self.as_ref().version, self.as_ref().method, self.path_decoded());
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-04-09 23:25:30 +02:00
let _ = writeln!(f, " params: {:?}", self.as_ref().params);
2017-10-19 08:43:50 +02:00
}
2018-04-09 23:25:30 +02:00
let _ = writeln!(f, " headers:");
2018-03-08 00:41:46 +01:00
for (key, val) in self.as_ref().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 http::{Uri, HttpTryFrom};
use router::Resource;
use resource::ResourceHandler;
2017-12-27 04:48:02 +01:00
use test::TestRequest;
2017-12-29 20:49:36 +01:00
use server::ServerSettings;
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_uri_mut() {
let mut req = HttpRequest::default();
assert_eq!(req.path(), "/");
*req.uri_mut() = Uri::try_from("/test").unwrap();
assert_eq!(req.path(), "/test");
}
2017-12-13 20:16:26 +01:00
#[test]
fn test_no_request_cookies() {
2017-12-27 04:48:02 +01:00
let req = HttpRequest::default();
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() {
2017-12-27 04:48:02 +01:00
let mut req = TestRequest::with_uri("/value/?id=test").finish();
2017-12-13 20:16:26 +01:00
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-02-22 14:48:18 +01:00
let (router, _) = Router::new("", ServerSettings::default(), routes);
2017-12-13 20:16:26 +01:00
assert!(router.recognize(&mut req).is_some());
assert_eq!(req.match_info().get("key"), Some("value"));
}
2017-12-07 01:26:27 +01:00
#[test]
fn test_url_for() {
2018-03-07 23:56:53 +01:00
let req2 = HttpRequest::default();
assert_eq!(req2.url_for("unknown", &["test"]),
Err(UrlGenerationError::RouterNotAvailable));
2017-12-07 01:26:27 +01:00
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-02-22 14:48:18 +01:00
let (router, _) = Router::new("/", ServerSettings::default(), routes);
2017-12-07 01:58:49 +01:00
assert!(router.has_route("/user/test.html"));
assert!(!router.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
assert_eq!(req.url_for("unknown", &["test"]),
Err(UrlGenerationError::ResourceNotFound));
assert_eq!(req.url_for("index", &["test"]),
Err(UrlGenerationError::NotEnoughElements));
let url = req.url_for("index", &["test", "html"]);
assert_eq!(url.ok().unwrap().as_str(), "http://www.rust-lang.org/user/test.html");
}
#[test]
fn test_url_for_with_prefix() {
2018-01-03 19:57:57 +01:00
let req = TestRequest::with_header(header::HOST, "www.rust-lang.org").finish();
let mut resource = ResourceHandler::<()>::default();
resource.name("index");
let routes = vec![(Resource::new("index", "/user/{name}.{ext}"), Some(resource))];
2018-02-22 14:48:18 +01:00
let (router, _) = Router::new("/prefix/", ServerSettings::default(), routes);
assert!(router.has_route("/user/test.html"));
assert!(!router.has_route("/prefix/user/test.html"));
let req = req.with_state(Rc::new(()), router);
let url = req.url_for("index", &["test", "html"]);
assert_eq!(url.ok().unwrap().as_str(),
"http://www.rust-lang.org/prefix/user/test.html");
}
#[test]
fn test_url_for_external() {
2018-01-03 19:57:57 +01:00
let req = HttpRequest::default();
let mut resource = ResourceHandler::<()>::default();
resource.name("index");
2018-02-22 14:48:18 +01:00
let routes = vec![
(Resource::external("youtube", "https://youtube.com/watch/{video_id}"), None)];
2018-02-22 14:48:18 +01:00
let (router, _) = Router::new::<()>("", ServerSettings::default(), routes);
assert!(!router.has_route("https://youtube.com/watch/unknown"));
2017-12-08 03:00:20 +01:00
let req = req.with_state(Rc::new(()), router);
let url = req.url_for("youtube", &["oHg5SJYRHA0"]);
assert_eq!(url.ok().unwrap().as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
}
2017-10-23 23:26:01 +02:00
}