repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-actors/tests/test_ws.rs
actix-web-actors/tests/test_ws.rs
use actix::prelude::*; use actix_http::ws::Codec; use actix_web::{web, App, HttpRequest}; use actix_web_actors::ws; use bytes::Bytes; use futures_util::{SinkExt as _, StreamExt as _}; struct Ws; impl Actor for Ws { type Context = ws::WebsocketContext<Self>; } impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for Ws { fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) { match msg { Ok(ws::Message::Ping(msg)) => ctx.pong(&msg), Ok(ws::Message::Text(text)) => ctx.text(text), Ok(ws::Message::Binary(bin)) => ctx.binary(bin), Ok(ws::Message::Close(reason)) => ctx.close(reason), _ => ctx.close(Some(ws::CloseCode::Error.into())), } } } const MAX_FRAME_SIZE: usize = 10_000; const DEFAULT_FRAME_SIZE: usize = 10; async fn common_test_code(mut srv: actix_test::TestServer, frame_size: usize) { // client service let mut framed = srv.ws().await.unwrap(); framed.send(ws::Message::Text("text".into())).await.unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text"))); let bytes = Bytes::from(vec![0; frame_size]); framed .send(ws::Message::Binary(bytes.clone())) .await .unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, ws::Frame::Binary(bytes)); framed.send(ws::Message::Ping("text".into())).await.unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, ws::Frame::Pong(Bytes::copy_from_slice(b"text"))); framed .send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))) .await .unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into()))); } #[actix_rt::test] async fn simple_builder() { let srv = actix_test::start(|| { App::new().service(web::resource("/").to( |req: HttpRequest, stream: web::Payload| async move { ws::WsResponseBuilder::new(Ws, &req, stream).start() }, )) }); common_test_code(srv, DEFAULT_FRAME_SIZE).await; } #[actix_rt::test] async fn builder_with_frame_size() { let srv = actix_test::start(|| { App::new().service(web::resource("/").to( |req: HttpRequest, stream: web::Payload| async move { ws::WsResponseBuilder::new(Ws, &req, stream) .frame_size(MAX_FRAME_SIZE) .start() }, )) }); common_test_code(srv, MAX_FRAME_SIZE).await; } #[actix_rt::test] async fn builder_with_frame_size_exceeded() { const MAX_FRAME_SIZE: usize = 64; let mut srv = actix_test::start(|| { App::new().service(web::resource("/").to( |req: HttpRequest, stream: web::Payload| async move { ws::WsResponseBuilder::new(Ws, &req, stream) .frame_size(MAX_FRAME_SIZE) .start() }, )) }); // client service let mut framed = srv.ws().await.unwrap(); // create a request with a frame size larger than expected let bytes = Bytes::from(vec![0; MAX_FRAME_SIZE + 1]); framed.send(ws::Message::Binary(bytes)).await.unwrap(); let frame = framed.next().await.unwrap().unwrap(); let close_reason = match frame { ws::Frame::Close(Some(reason)) => reason, _ => panic!("close frame expected"), }; assert_eq!(close_reason.code, ws::CloseCode::Error); } #[actix_rt::test] async fn builder_with_codec() { let srv = actix_test::start(|| { App::new().service(web::resource("/").to( |req: HttpRequest, stream: web::Payload| async move { ws::WsResponseBuilder::new(Ws, &req, stream) .codec(Codec::new()) .start() }, )) }); common_test_code(srv, DEFAULT_FRAME_SIZE).await; } #[actix_rt::test] async fn builder_with_protocols() { let srv = actix_test::start(|| { App::new().service(web::resource("/").to( |req: HttpRequest, stream: web::Payload| async move { ws::WsResponseBuilder::new(Ws, &req, stream) .protocols(&["A", "B"]) .start() }, )) }); common_test_code(srv, DEFAULT_FRAME_SIZE).await; } #[actix_rt::test] async fn builder_with_codec_and_frame_size() { let srv = actix_test::start(|| { App::new().service(web::resource("/").to( |req: HttpRequest, stream: web::Payload| async move { ws::WsResponseBuilder::new(Ws, &req, stream) .codec(Codec::new()) .frame_size(MAX_FRAME_SIZE) .start() }, )) }); common_test_code(srv, DEFAULT_FRAME_SIZE).await; } #[actix_rt::test] async fn builder_full() { let srv = actix_test::start(|| { App::new().service(web::resource("/").to( |req: HttpRequest, stream: web::Payload| async move { ws::WsResponseBuilder::new(Ws, &req, stream) .frame_size(MAX_FRAME_SIZE) .codec(Codec::new()) .protocols(&["A", "B"]) .start() }, )) }); common_test_code(srv, MAX_FRAME_SIZE).await; } #[actix_rt::test] async fn simple_start() { let srv = actix_test::start(|| { App::new().service(web::resource("/").to( |req: HttpRequest, stream: web::Payload| async move { ws::start(Ws, &req, stream) }, )) }); common_test_code(srv, DEFAULT_FRAME_SIZE).await; }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/test.rs
awc/src/test.rs
//! Test helpers for actix http client to use during testing. use actix_http::{h1, header::TryIntoHeaderPair, Payload, ResponseHead, StatusCode, Version}; use bytes::Bytes; #[cfg(feature = "cookies")] use crate::cookie::{Cookie, CookieJar}; use crate::ClientResponse; /// Test `ClientResponse` builder pub struct TestResponse { head: ResponseHead, #[cfg(feature = "cookies")] cookies: CookieJar, payload: Option<Payload>, } impl Default for TestResponse { fn default() -> TestResponse { TestResponse { head: ResponseHead::new(StatusCode::OK), #[cfg(feature = "cookies")] cookies: CookieJar::new(), payload: None, } } } impl TestResponse { /// Create TestResponse and set header pub fn with_header(header: impl TryIntoHeaderPair) -> Self { Self::default().insert_header(header) } /// Set HTTP version of this response pub fn version(mut self, ver: Version) -> Self { self.head.version = ver; self } /// Insert a header pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self { if let Ok((key, value)) = header.try_into_pair() { self.head.headers.insert(key, value); return self; } panic!("Can not set header"); } /// Append a header pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self { if let Ok((key, value)) = header.try_into_pair() { self.head.headers.append(key, value); return self; } panic!("Can not create header"); } /// Set cookie for this response #[cfg(feature = "cookies")] pub fn cookie(mut self, cookie: Cookie<'_>) -> Self { self.cookies.add(cookie.into_owned()); self } /// Set response's payload pub fn set_payload<B: Into<Bytes>>(mut self, data: B) -> Self { self.payload = Some(Payload::from(data.into())); self } /// Complete response creation and generate `ClientResponse` instance pub fn finish(self) -> ClientResponse { // allow unused mut when cookies feature is disabled #[allow(unused_mut)] let mut head = self.head; #[cfg(feature = "cookies")] for cookie in self.cookies.delta() { use actix_http::header::{self, HeaderValue}; head.headers.insert( header::SET_COOKIE, HeaderValue::from_str(&cookie.encoded().to_string()).unwrap(), ); } if let Some(pl) = self.payload { ClientResponse::new(head, pl) } else { let (_, payload) = h1::Payload::create(true); ClientResponse::new(head, payload.into()) } } } #[cfg(test)] mod tests { use std::time::SystemTime; use actix_http::header::HttpDate; use super::*; use crate::http::header; #[test] fn test_basics() { let res = TestResponse::default() .version(Version::HTTP_2) .insert_header((header::DATE, HttpDate::from(SystemTime::now()))) .cookie(cookie::Cookie::build("name", "value").finish()) .finish(); assert!(res.headers().contains_key(header::SET_COOKIE)); assert!(res.headers().contains_key(header::DATE)); assert_eq!(res.version(), Version::HTTP_2); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/sender.rs
awc/src/sender.rs
use std::{ future::Future, net, pin::Pin, rc::Rc, task::{Context, Poll}, time::Duration, }; use actix_http::{ body::{BodyStream, MessageBody}, error::HttpError, header::{self, HeaderMap, HeaderName, TryIntoHeaderValue}, RequestHead, RequestHeadType, }; #[cfg(feature = "__compress")] use actix_http::{encoding::Decoder, header::ContentEncoding, Payload}; use actix_rt::time::{sleep, Sleep}; use bytes::Bytes; use derive_more::From; use futures_core::Stream; use serde::Serialize; use crate::{ any_body::AnyBody, client::ClientConfig, error::{FreezeRequestError, InvalidUrl, SendRequestError}, BoxError, ClientResponse, ConnectRequest, ConnectResponse, }; #[derive(Debug, From)] pub(crate) enum PrepForSendingError { Url(InvalidUrl), Http(HttpError), Json(serde_json::Error), Form(serde_urlencoded::ser::Error), } impl From<PrepForSendingError> for FreezeRequestError { fn from(err: PrepForSendingError) -> FreezeRequestError { match err { PrepForSendingError::Url(err) => FreezeRequestError::Url(err), PrepForSendingError::Http(err) => FreezeRequestError::Http(err), PrepForSendingError::Json(err) => { FreezeRequestError::Custom(Box::new(err), Box::new("json serialization error")) } PrepForSendingError::Form(err) => { FreezeRequestError::Custom(Box::new(err), Box::new("form serialization error")) } } } } impl From<PrepForSendingError> for SendRequestError { fn from(err: PrepForSendingError) -> SendRequestError { match err { PrepForSendingError::Url(err) => SendRequestError::Url(err), PrepForSendingError::Http(err) => SendRequestError::Http(err), PrepForSendingError::Json(err) => { SendRequestError::Custom(Box::new(err), Box::new("json serialization error")) } PrepForSendingError::Form(err) => { SendRequestError::Custom(Box::new(err), Box::new("form serialization error")) } } } } /// Future that sends request's payload and resolves to a server response. #[must_use = "futures do nothing unless polled"] pub enum SendClientRequest { Fut( Pin<Box<dyn Future<Output = Result<ConnectResponse, SendRequestError>>>>, // FIXME: use a pinned Sleep instead of box. Option<Pin<Box<Sleep>>>, bool, ), Err(Option<SendRequestError>), } impl SendClientRequest { pub(crate) fn new( send: Pin<Box<dyn Future<Output = Result<ConnectResponse, SendRequestError>>>>, response_decompress: bool, timeout: Option<Duration>, ) -> SendClientRequest { let delay = timeout.map(|d| Box::pin(sleep(d))); SendClientRequest::Fut(send, delay, response_decompress) } } #[cfg(feature = "__compress")] impl Future for SendClientRequest { type Output = Result<ClientResponse<Decoder<Payload>>, SendRequestError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); match this { SendClientRequest::Fut(send, delay, response_decompress) => { if let Some(delay) = delay { if delay.as_mut().poll(cx).is_ready() { return Poll::Ready(Err(SendRequestError::Timeout)); } } let res = futures_core::ready!(send.as_mut().poll(cx)).map(|res| { res.into_client_response() ._timeout(delay.take()) .map_body(|head, payload| { if *response_decompress { Payload::Stream { payload: Decoder::from_headers(payload, &head.headers), } } else { Payload::Stream { payload: Decoder::new(payload, ContentEncoding::Identity), } } }) }); Poll::Ready(res) } SendClientRequest::Err(ref mut err) => match err.take() { Some(err) => Poll::Ready(Err(err)), None => panic!("Attempting to call completed future"), }, } } } #[cfg(not(feature = "__compress"))] impl Future for SendClientRequest { type Output = Result<ClientResponse, SendRequestError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); match this { SendClientRequest::Fut(send, delay, _) => { if let Some(delay) = delay { if delay.as_mut().poll(cx).is_ready() { return Poll::Ready(Err(SendRequestError::Timeout)); } } send.as_mut() .poll(cx) .map_ok(|res| res.into_client_response()._timeout(delay.take())) } SendClientRequest::Err(ref mut err) => match err.take() { Some(err) => Poll::Ready(Err(err)), None => panic!("Attempting to call completed future"), }, } } } impl From<SendRequestError> for SendClientRequest { fn from(err: SendRequestError) -> Self { SendClientRequest::Err(Some(err)) } } impl From<HttpError> for SendClientRequest { fn from(err: HttpError) -> Self { SendClientRequest::Err(Some(err.into())) } } impl From<PrepForSendingError> for SendClientRequest { fn from(err: PrepForSendingError) -> Self { SendClientRequest::Err(Some(err.into())) } } #[derive(Debug)] pub(crate) enum RequestSender { Owned(RequestHead), Rc(Rc<RequestHead>, Option<HeaderMap>), } impl RequestSender { pub(crate) fn send_body( self, addr: Option<net::SocketAddr>, response_decompress: bool, timeout: Option<Duration>, config: &ClientConfig, body: impl MessageBody + 'static, ) -> SendClientRequest { let req = match self { RequestSender::Owned(head) => ConnectRequest::Client( RequestHeadType::Owned(head), AnyBody::from_message_body(body).into_boxed(), addr, ), RequestSender::Rc(head, extra_headers) => ConnectRequest::Client( RequestHeadType::Rc(head, extra_headers), AnyBody::from_message_body(body).into_boxed(), addr, ), }; let fut = config.connector.call(req); SendClientRequest::new(fut, response_decompress, timeout.or(config.timeout)) } pub(crate) fn send_json( mut self, addr: Option<net::SocketAddr>, response_decompress: bool, timeout: Option<Duration>, config: &ClientConfig, value: impl Serialize, ) -> SendClientRequest { let body = match serde_json::to_string(&value) { Ok(body) => body, Err(err) => return PrepForSendingError::Json(err).into(), }; if let Err(err) = self.set_header_if_none(header::CONTENT_TYPE, "application/json") { return err.into(); } self.send_body(addr, response_decompress, timeout, config, body) } pub(crate) fn send_form( mut self, addr: Option<net::SocketAddr>, response_decompress: bool, timeout: Option<Duration>, config: &ClientConfig, value: impl Serialize, ) -> SendClientRequest { let body = match serde_urlencoded::to_string(value) { Ok(body) => body, Err(err) => return PrepForSendingError::Form(err).into(), }; // set content-type if let Err(err) = self.set_header_if_none(header::CONTENT_TYPE, "application/x-www-form-urlencoded") { return err.into(); } self.send_body(addr, response_decompress, timeout, config, body) } pub(crate) fn send_stream<S, E>( self, addr: Option<net::SocketAddr>, response_decompress: bool, timeout: Option<Duration>, config: &ClientConfig, stream: S, ) -> SendClientRequest where S: Stream<Item = Result<Bytes, E>> + 'static, E: Into<BoxError> + 'static, { self.send_body( addr, response_decompress, timeout, config, BodyStream::new(stream), ) } pub(crate) fn send( self, addr: Option<net::SocketAddr>, response_decompress: bool, timeout: Option<Duration>, config: &ClientConfig, ) -> SendClientRequest { self.send_body(addr, response_decompress, timeout, config, ()) } fn set_header_if_none<V>(&mut self, key: HeaderName, value: V) -> Result<(), HttpError> where V: TryIntoHeaderValue, { match self { RequestSender::Owned(head) => { if !head.headers.contains_key(&key) { match value.try_into_value() { Ok(value) => { head.headers.insert(key, value); } Err(err) => return Err(err.into()), } } } RequestSender::Rc(head, extra_headers) => { if !head.headers.contains_key(&key) && !extra_headers.iter().any(|h| h.contains_key(&key)) { match value.try_into_value() { Ok(v) => { let h = extra_headers.get_or_insert(HeaderMap::new()); h.insert(key, v) } Err(err) => return Err(err.into()), }; } } } Ok(()) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/frozen.rs
awc/src/frozen.rs
use std::{net, rc::Rc, time::Duration}; use actix_http::{ body::MessageBody, error::HttpError, header::{HeaderMap, TryIntoHeaderPair}, Method, RequestHead, Uri, }; use bytes::Bytes; use futures_core::Stream; use serde::Serialize; use crate::{ client::ClientConfig, sender::{RequestSender, SendClientRequest}, BoxError, }; /// `FrozenClientRequest` struct represents cloneable client request. /// /// It could be used to send same request multiple times. #[derive(Clone)] pub struct FrozenClientRequest { pub(crate) head: Rc<RequestHead>, pub(crate) addr: Option<net::SocketAddr>, pub(crate) response_decompress: bool, pub(crate) timeout: Option<Duration>, pub(crate) config: ClientConfig, } impl FrozenClientRequest { /// Get HTTP URI of request pub fn get_uri(&self) -> &Uri { &self.head.uri } /// Get HTTP method of this request pub fn get_method(&self) -> &Method { &self.head.method } /// Returns request's headers. pub fn headers(&self) -> &HeaderMap { &self.head.headers } /// Send a body. pub fn send_body<B>(&self, body: B) -> SendClientRequest where B: MessageBody + 'static, { RequestSender::Rc(Rc::clone(&self.head), None).send_body( self.addr, self.response_decompress, self.timeout, &self.config, body, ) } /// Send a json body. pub fn send_json<T: Serialize>(&self, value: &T) -> SendClientRequest { RequestSender::Rc(Rc::clone(&self.head), None).send_json( self.addr, self.response_decompress, self.timeout, &self.config, value, ) } /// Send an urlencoded body. pub fn send_form<T: Serialize>(&self, value: &T) -> SendClientRequest { RequestSender::Rc(Rc::clone(&self.head), None).send_form( self.addr, self.response_decompress, self.timeout, &self.config, value, ) } /// Send a streaming body. pub fn send_stream<S, E>(&self, stream: S) -> SendClientRequest where S: Stream<Item = Result<Bytes, E>> + 'static, E: Into<BoxError> + 'static, { RequestSender::Rc(Rc::clone(&self.head), None).send_stream( self.addr, self.response_decompress, self.timeout, &self.config, stream, ) } /// Send an empty body. pub fn send(&self) -> SendClientRequest { RequestSender::Rc(Rc::clone(&self.head), None).send( self.addr, self.response_decompress, self.timeout, &self.config, ) } /// Clones this `FrozenClientRequest`, returning a new one with extra headers added. pub fn extra_headers(&self, extra_headers: HeaderMap) -> FrozenSendBuilder { FrozenSendBuilder::new(self.clone(), extra_headers) } /// Clones this `FrozenClientRequest`, returning a new one with the extra header added. pub fn extra_header(&self, header: impl TryIntoHeaderPair) -> FrozenSendBuilder { self.extra_headers(HeaderMap::new()).extra_header(header) } } /// Builder that allows to modify extra headers. pub struct FrozenSendBuilder { req: FrozenClientRequest, extra_headers: HeaderMap, err: Option<HttpError>, } impl FrozenSendBuilder { pub(crate) fn new(req: FrozenClientRequest, extra_headers: HeaderMap) -> Self { Self { req, extra_headers, err: None, } } /// Insert a header, it overrides existing header in `FrozenClientRequest`. pub fn extra_header(mut self, header: impl TryIntoHeaderPair) -> Self { match header.try_into_pair() { Ok((key, value)) => { self.extra_headers.insert(key, value); } Err(err) => self.err = Some(err.into()), } self } /// Complete request construction and send a body. pub fn send_body(self, body: impl MessageBody + 'static) -> SendClientRequest { if let Some(err) = self.err { return err.into(); } RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_body( self.req.addr, self.req.response_decompress, self.req.timeout, &self.req.config, body, ) } /// Complete request construction and send a json body. pub fn send_json(self, value: impl Serialize) -> SendClientRequest { if let Some(err) = self.err { return err.into(); } RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_json( self.req.addr, self.req.response_decompress, self.req.timeout, &self.req.config, value, ) } /// Complete request construction and send an urlencoded body. pub fn send_form(self, value: impl Serialize) -> SendClientRequest { if let Some(err) = self.err { return err.into(); } RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_form( self.req.addr, self.req.response_decompress, self.req.timeout, &self.req.config, value, ) } /// Complete request construction and send a streaming body. pub fn send_stream<S, E>(self, stream: S) -> SendClientRequest where S: Stream<Item = Result<Bytes, E>> + 'static, E: Into<BoxError> + 'static, { if let Some(err) = self.err { return err.into(); } RequestSender::Rc(self.req.head, Some(self.extra_headers)).send_stream( self.req.addr, self.req.response_decompress, self.req.timeout, &self.req.config, stream, ) } /// Complete request construction and send an empty body. pub fn send(self) -> SendClientRequest { if let Some(err) = self.err { return err.into(); } RequestSender::Rc(self.req.head, Some(self.extra_headers)).send( self.req.addr, self.req.response_decompress, self.req.timeout, &self.req.config, ) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/builder.rs
awc/src/builder.rs
use std::{fmt, net::IpAddr, rc::Rc, time::Duration}; use actix_http::{ error::HttpError, header::{self, HeaderMap, HeaderName, TryIntoHeaderPair}, Uri, }; use actix_rt::net::{ActixStream, TcpStream}; use actix_service::{boxed, Service}; use base64::prelude::*; use crate::{ client::{ ClientConfig, ConnectInfo, Connector, ConnectorService, TcpConnectError, TcpConnection, }, connect::DefaultConnector, error::SendRequestError, middleware::{NestTransform, Redirect, Transform}, Client, ConnectRequest, ConnectResponse, }; /// An HTTP Client builder /// /// This type can be used to construct an instance of `Client` through a /// builder-like pattern. pub struct ClientBuilder<S = (), M = ()> { max_http_version: Option<http::Version>, stream_window_size: Option<u32>, conn_window_size: Option<u32>, fundamental_headers: bool, default_headers: HeaderMap, timeout: Option<Duration>, connector: Connector<S>, middleware: M, local_address: Option<IpAddr>, max_redirects: u8, } impl ClientBuilder { /// Create a new ClientBuilder with default settings /// /// Note: If the `rustls-0_23` feature is enabled and neither `rustls-0_23-native-roots` nor /// `rustls-0_23-webpki-roots` are enabled, this ClientBuilder will build without TLS. In order /// to enable TLS in this scenario, a custom `Connector` _must_ be added to the builder before /// finishing construction. #[allow(clippy::new_ret_no_self)] pub fn new() -> ClientBuilder< impl Service< ConnectInfo<Uri>, Response = TcpConnection<Uri, TcpStream>, Error = TcpConnectError, > + Clone, (), > { ClientBuilder { max_http_version: None, stream_window_size: None, conn_window_size: None, fundamental_headers: true, default_headers: HeaderMap::new(), timeout: Some(Duration::from_secs(5)), connector: Connector::new(), middleware: (), local_address: None, max_redirects: 10, } } } impl<S, Io, M> ClientBuilder<S, M> where S: Service<ConnectInfo<Uri>, Response = TcpConnection<Uri, Io>, Error = TcpConnectError> + Clone + 'static, Io: ActixStream + fmt::Debug + 'static, { /// Use custom connector service. pub fn connector<S1, Io1>(self, connector: Connector<S1>) -> ClientBuilder<S1, M> where S1: Service<ConnectInfo<Uri>, Response = TcpConnection<Uri, Io1>, Error = TcpConnectError> + Clone + 'static, Io1: ActixStream + fmt::Debug + 'static, { ClientBuilder { middleware: self.middleware, fundamental_headers: self.fundamental_headers, default_headers: self.default_headers, timeout: self.timeout, local_address: self.local_address, connector, max_http_version: self.max_http_version, stream_window_size: self.stream_window_size, conn_window_size: self.conn_window_size, max_redirects: self.max_redirects, } } /// Set request timeout /// /// Request timeout is the total time before a response must be received. /// Default value is 5 seconds. pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } /// Disable request timeout. pub fn disable_timeout(mut self) -> Self { self.timeout = None; self } /// Set local IP Address the connector would use for establishing connection. pub fn local_address(mut self, addr: IpAddr) -> Self { self.local_address = Some(addr); self } /// Maximum supported HTTP major version. /// /// Supported versions are HTTP/1.1 and HTTP/2. pub fn max_http_version(mut self, val: http::Version) -> Self { self.max_http_version = Some(val); self } /// Do not follow redirects. /// /// Redirects are allowed by default. pub fn disable_redirects(mut self) -> Self { self.max_redirects = 0; self } /// Set max number of redirects. /// /// Max redirects is set to 10 by default. pub fn max_redirects(mut self, num: u8) -> Self { self.max_redirects = num; self } /// Indicates the initial window size (in octets) for /// HTTP2 stream-level flow control for received data. /// /// The default value is 65,535 and is good for APIs, but not for big objects. pub fn initial_window_size(mut self, size: u32) -> Self { self.stream_window_size = Some(size); self } /// Indicates the initial window size (in octets) for /// HTTP2 connection-level flow control for received data. /// /// The default value is 65,535 and is good for APIs, but not for big objects. pub fn initial_connection_window_size(mut self, size: u32) -> Self { self.conn_window_size = Some(size); self } /// Do not add fundamental default request headers. /// /// By default `Date` and `User-Agent` headers are set. pub fn no_default_headers(mut self) -> Self { self.fundamental_headers = false; self } /// Add default header. /// /// Headers added by this method get added to every request unless overridden by other methods. /// /// # Panics /// Panics if header name or value is invalid. pub fn add_default_header(mut self, header: impl TryIntoHeaderPair) -> Self { match header.try_into_pair() { Ok((key, value)) => self.default_headers.append(key, value), Err(err) => panic!("Header error: {:?}", err.into()), } self } #[doc(hidden)] #[deprecated(since = "3.0.0", note = "Prefer `add_default_header((key, value))`.")] pub fn header<K, V>(mut self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: fmt::Debug + Into<HttpError>, V: header::TryIntoHeaderValue, V::Error: fmt::Debug, { match HeaderName::try_from(key) { Ok(key) => match value.try_into_value() { Ok(value) => { self.default_headers.append(key, value); } Err(err) => log::error!("Header value error: {:?}", err), }, Err(err) => log::error!("Header name error: {:?}", err), } self } /// Set client wide HTTP basic authorization header pub fn basic_auth<N>(self, username: N, password: Option<&str>) -> Self where N: fmt::Display, { let auth = match password { Some(password) => format!("{}:{}", username, password), None => format!("{}:", username), }; self.add_default_header(( header::AUTHORIZATION, format!("Basic {}", BASE64_STANDARD.encode(auth)), )) } /// Set client wide HTTP bearer authentication header pub fn bearer_auth<T>(self, token: T) -> Self where T: fmt::Display, { self.add_default_header((header::AUTHORIZATION, format!("Bearer {}", token))) } /// Registers middleware, in the form of a middleware component (type), that runs during inbound /// and/or outbound processing in the request life-cycle (request -> response), /// modifying request/response as necessary, across all requests managed by the `Client`. pub fn wrap<S1, M1>(self, mw: M1) -> ClientBuilder<S, NestTransform<M, M1, S1, ConnectRequest>> where M: Transform<S1, ConnectRequest>, M1: Transform<M::Transform, ConnectRequest>, { ClientBuilder { middleware: NestTransform::new(self.middleware, mw), fundamental_headers: self.fundamental_headers, max_http_version: self.max_http_version, stream_window_size: self.stream_window_size, conn_window_size: self.conn_window_size, default_headers: self.default_headers, timeout: self.timeout, connector: self.connector, local_address: self.local_address, max_redirects: self.max_redirects, } } /// Finish build process and create `Client` instance. pub fn finish(self) -> Client where M: Transform<DefaultConnector<ConnectorService<S, Io>>, ConnectRequest> + 'static, M::Transform: Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError>, { let max_redirects = self.max_redirects; if max_redirects > 0 { self.wrap(Redirect::new().max_redirect_times(max_redirects)) ._finish() } else { self._finish() } } fn _finish(self) -> Client where M: Transform<DefaultConnector<ConnectorService<S, Io>>, ConnectRequest> + 'static, M::Transform: Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError>, { let mut connector = self.connector; if let Some(val) = self.max_http_version { connector = connector.max_http_version(val); }; if let Some(val) = self.conn_window_size { connector = connector.initial_connection_window_size(val) }; if let Some(val) = self.stream_window_size { connector = connector.initial_window_size(val) }; if let Some(val) = self.local_address { connector = connector.local_address(val); } let connector = DefaultConnector::new(connector.finish()); let connector = boxed::rc_service(self.middleware.new_transform(connector)); Client(ClientConfig { default_headers: Rc::new(self.default_headers), timeout: self.timeout, connector, }) } } #[cfg(test)] mod tests { use super::*; #[test] fn client_basic_auth() { let client = ClientBuilder::new().basic_auth("username", Some("password")); assert_eq!( client .default_headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" ); let client = ClientBuilder::new().basic_auth("username", None); assert_eq!( client .default_headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Basic dXNlcm5hbWU6" ); } #[test] fn client_bearer_auth() { let client = ClientBuilder::new().bearer_auth("someS3cr3tAutht0k3n"); assert_eq!( client .default_headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Bearer someS3cr3tAutht0k3n" ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/lib.rs
awc/src/lib.rs
//! `awc` is an asynchronous HTTP and WebSocket client library. //! //! # `GET` Requests //! ```no_run //! # #[actix_rt::main] //! # async fn main() -> Result<(), awc::error::SendRequestError> { //! // create client //! let mut client = awc::Client::default(); //! //! // construct request //! let req = client.get("http://www.rust-lang.org") //! .insert_header(("User-Agent", "awc/3.0")); //! //! // send request and await response //! let res = req.send().await?; //! println!("Response: {:?}", res); //! # Ok(()) //! # } //! ``` //! //! # `POST` Requests //! ## Raw Body //! ```no_run //! # #[actix_rt::main] //! # async fn main() -> Result<(), awc::error::SendRequestError> { //! let mut client = awc::Client::default(); //! let response = client.post("http://httpbin.org/post") //! .send_body("Raw body contents") //! .await?; //! # Ok(()) //! # } //! ``` //! //! ## JSON //! ```no_run //! # #[actix_rt::main] //! # async fn main() -> Result<(), awc::error::SendRequestError> { //! let request = serde_json::json!({ //! "lang": "rust", //! "body": "json" //! }); //! //! let mut client = awc::Client::default(); //! let response = client.post("http://httpbin.org/post") //! .send_json(&request) //! .await?; //! # Ok(()) //! # } //! ``` //! //! ## URL Encoded Form //! ```no_run //! # #[actix_rt::main] //! # async fn main() -> Result<(), awc::error::SendRequestError> { //! let params = [("foo", "bar"), ("baz", "quux")]; //! //! let mut client = awc::Client::default(); //! let response = client.post("http://httpbin.org/post") //! .send_form(&params) //! .await?; //! # Ok(()) //! # } //! ``` //! //! # Response Compression //! All [official][iana-encodings] and common content encoding codecs are supported, optionally. //! //! The `Accept-Encoding` header will automatically be populated with enabled codecs and added to //! outgoing requests, allowing servers to select their `Content-Encoding` accordingly. //! //! Feature flags enable these codecs according to the table below. By default, all `compress-*` //! features are enabled. //! //! | Feature | Codecs | //! | ----------------- | ------------- | //! | `compress-brotli` | brotli | //! | `compress-gzip` | gzip, deflate | //! | `compress-zstd` | zstd | //! //! [iana-encodings]: https://www.iana.org/assignments/http-parameters/http-parameters.xhtml#content-coding //! //! # WebSockets //! ```no_run //! # #[actix_rt::main] //! # async fn main() -> Result<(), Box<dyn std::error::Error>> { //! use futures_util::{SinkExt as _, StreamExt as _}; //! //! let (_resp, mut connection) = awc::Client::new() //! .ws("ws://echo.websocket.org") //! .connect() //! .await?; //! //! connection //! .send(awc::ws::Message::Text("Echo".into())) //! .await?; //! //! let response = connection.next().await.unwrap()?; //! assert_eq!(response, awc::ws::Frame::Text("Echo".into())); //! # Ok(()) //! # } //! ``` #![allow(unknown_lints)] // temp: #[allow(non_local_definitions)] #![allow( clippy::type_complexity, clippy::borrow_interior_mutable_const, clippy::needless_doctest_main )] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_cfg))] pub use actix_http::body; #[cfg(feature = "cookies")] pub use cookie; mod any_body; mod builder; mod client; mod connect; pub mod error; mod frozen; pub mod middleware; mod request; mod responses; mod sender; pub mod test; pub mod ws; pub mod http { //! Various HTTP related types. // TODO: figure out how best to expose http::Error vs actix_http::Error pub use actix_http::{header, uri, ConnectionType, Error, Method, StatusCode, Uri, Version}; } #[allow(deprecated)] pub use self::responses::{ClientResponse, JsonBody, MessageBody, ResponseBody}; pub use self::{ builder::ClientBuilder, client::{Client, Connect, Connector}, connect::{BoxConnectorService, BoxedSocket, ConnectRequest, ConnectResponse}, frozen::{FrozenClientRequest, FrozenSendBuilder}, request::ClientRequest, sender::SendClientRequest, }; pub(crate) type BoxError = Box<dyn std::error::Error>;
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/connect.rs
awc/src/connect.rs
use std::{ future::Future, net, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_codec::Framed; use actix_http::{h1::ClientCodec, Payload, RequestHead, RequestHeadType, ResponseHead}; use actix_service::Service; use futures_core::{future::LocalBoxFuture, ready}; use crate::{ any_body::AnyBody, client::{Connect as ClientConnect, ConnectError, Connection, ConnectionIo, SendRequestError}, ClientResponse, }; pub type BoxConnectorService = Rc< dyn Service< ConnectRequest, Response = ConnectResponse, Error = SendRequestError, Future = LocalBoxFuture<'static, Result<ConnectResponse, SendRequestError>>, >, >; pub type BoxedSocket = Box<dyn ConnectionIo>; /// Combined HTTP and WebSocket request type received by connection service. pub enum ConnectRequest { /// Standard HTTP request. /// /// Contains the request head, body type, and optional pre-resolved socket address. Client(RequestHeadType, AnyBody, Option<net::SocketAddr>), /// Tunnel used by WebSocket connection requests. /// /// Contains the request head and optional pre-resolved socket address. Tunnel(RequestHead, Option<net::SocketAddr>), } /// Combined HTTP response & WebSocket tunnel type returned from connection service. pub enum ConnectResponse { /// Standard HTTP response. Client(ClientResponse), /// Tunnel used for WebSocket communication. /// /// Contains response head and framed HTTP/1.1 codec. Tunnel(ResponseHead, Framed<BoxedSocket, ClientCodec>), } impl ConnectResponse { /// Unwraps type into HTTP response. /// /// # Panics /// Panics if enum variant is not `Client`. pub fn into_client_response(self) -> ClientResponse { match self { ConnectResponse::Client(res) => res, _ => { panic!("ClientResponse only reachable with ConnectResponse::ClientResponse variant") } } } /// Unwraps type into WebSocket tunnel response. /// /// # Panics /// Panics if enum variant is not `Tunnel`. pub fn into_tunnel_response(self) -> (ResponseHead, Framed<BoxedSocket, ClientCodec>) { match self { ConnectResponse::Tunnel(head, framed) => (head, framed), _ => { panic!("TunnelResponse only reachable with ConnectResponse::TunnelResponse variant") } } } } pub struct DefaultConnector<S> { connector: S, } impl<S> DefaultConnector<S> { pub(crate) fn new(connector: S) -> Self { Self { connector } } } impl<S, Io> Service<ConnectRequest> for DefaultConnector<S> where S: Service<ClientConnect, Error = ConnectError, Response = Connection<Io>>, Io: ConnectionIo, { type Response = ConnectResponse; type Error = SendRequestError; type Future = ConnectRequestFuture<S::Future, Io>; actix_service::forward_ready!(connector); fn call(&self, req: ConnectRequest) -> Self::Future { // connect to the host let fut = match req { ConnectRequest::Client(ref head, .., addr) => self.connector.call(ClientConnect { uri: head.as_ref().uri.clone(), addr, }), ConnectRequest::Tunnel(ref head, addr) => self.connector.call(ClientConnect { uri: head.uri.clone(), addr, }), }; ConnectRequestFuture::Connection { fut, req: Some(req), } } } pin_project_lite::pin_project! { #[project = ConnectRequestProj] pub enum ConnectRequestFuture<Fut, Io> where Io: ConnectionIo { Connection { #[pin] fut: Fut, req: Option<ConnectRequest> }, Client { fut: LocalBoxFuture<'static, Result<(ResponseHead, Payload), SendRequestError>> }, Tunnel { fut: LocalBoxFuture< 'static, Result<(ResponseHead, Framed<Connection<Io>, ClientCodec>), SendRequestError>, >, } } } impl<Fut, Io> Future for ConnectRequestFuture<Fut, Io> where Fut: Future<Output = Result<Connection<Io>, ConnectError>>, Io: ConnectionIo, { type Output = Result<ConnectResponse, SendRequestError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match self.as_mut().project() { ConnectRequestProj::Connection { fut, req } => { let connection = ready!(fut.poll(cx))?; let req = req.take().unwrap(); match req { ConnectRequest::Client(head, body, ..) => { // send request let fut = ConnectRequestFuture::Client { fut: connection.send_request(head, body), }; self.set(fut); } ConnectRequest::Tunnel(head, ..) => { // send request let fut = ConnectRequestFuture::Tunnel { fut: connection.open_tunnel(RequestHeadType::from(head)), }; self.set(fut); } } self.poll(cx) } ConnectRequestProj::Client { fut } => { let (head, payload) = ready!(fut.as_mut().poll(cx))?; Poll::Ready(Ok(ConnectResponse::Client(ClientResponse::new( head, payload, )))) } ConnectRequestProj::Tunnel { fut } => { let (head, framed) = ready!(fut.as_mut().poll(cx))?; let framed = framed.into_map_io(|io| Box::new(io) as _); Poll::Ready(Ok(ConnectResponse::Tunnel(head, framed))) } } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/error.rs
awc/src/error.rs
//! HTTP client errors // TODO: figure out how best to expose http::Error vs actix_http::Error pub use actix_http::{ error::{HttpError, PayloadError}, header::HeaderValue, ws::{HandshakeError as WsHandshakeError, ProtocolError as WsProtocolError}, StatusCode, }; use derive_more::{Display, From}; use serde_json::error::Error as JsonError; pub use crate::client::{ConnectError, FreezeRequestError, InvalidUrl, SendRequestError}; // TODO: address display, error, and from impls /// Websocket client error #[derive(Debug, Display, From)] pub enum WsClientError { /// Invalid response status #[display("Invalid response status")] InvalidResponseStatus(StatusCode), /// Invalid upgrade header #[display("Invalid upgrade header")] InvalidUpgradeHeader, /// Invalid connection header #[display("Invalid connection header")] InvalidConnectionHeader(HeaderValue), /// Missing Connection header #[display("Missing Connection header")] MissingConnectionHeader, /// Missing Sec-Websocket-Accept header #[display("Missing Sec-Websocket-Accept header")] MissingWebSocketAcceptHeader, /// Invalid challenge response #[display("Invalid challenge response")] InvalidChallengeResponse([u8; 28], HeaderValue), /// Protocol error #[display("{}", _0)] Protocol(WsProtocolError), /// Send request error #[display("{}", _0)] SendRequest(SendRequestError), } impl std::error::Error for WsClientError {} impl From<InvalidUrl> for WsClientError { fn from(err: InvalidUrl) -> Self { WsClientError::SendRequest(err.into()) } } impl From<HttpError> for WsClientError { fn from(err: HttpError) -> Self { WsClientError::SendRequest(err.into()) } } /// A set of errors that can occur during parsing json payloads #[derive(Debug, Display, From)] pub enum JsonPayloadError { /// Content type error #[display("Content type error")] ContentType, /// Deserialize error #[display("Json deserialize error: {}", _0)] Deserialize(JsonError), /// Payload error #[display("Error that occur during reading payload: {}", _0)] Payload(PayloadError), } impl std::error::Error for JsonPayloadError {}
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/any_body.rs
awc/src/any_body.rs
use std::{ fmt, mem, pin::Pin, task::{Context, Poll}, }; use actix_http::body::{BodySize, BoxBody, MessageBody}; use bytes::Bytes; use pin_project_lite::pin_project; pin_project! { /// Represents various types of HTTP message body. #[derive(Clone)] #[project = AnyBodyProj] pub enum AnyBody<B = BoxBody> { /// Empty response. `Content-Length` header is not set. None, /// Complete, in-memory response body. Bytes { body: Bytes }, /// Generic / Other message body. Body { #[pin] body: B }, } } impl AnyBody { /// Constructs a "body" representing an empty response. pub fn none() -> Self { Self::None } /// Constructs a new, 0-length body. pub fn empty() -> Self { Self::Bytes { body: Bytes::new() } } /// Create boxed body from generic message body. pub fn new_boxed<B>(body: B) -> Self where B: MessageBody + 'static, { Self::Body { body: body.boxed() } } /// Constructs new `AnyBody` instance from a slice of bytes by copying it. /// /// If your bytes container is owned, it may be cheaper to use a `From` impl. pub fn copy_from_slice(s: &[u8]) -> Self { Self::Bytes { body: Bytes::copy_from_slice(s), } } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `copy_from_slice`.")] pub fn from_slice(s: &[u8]) -> Self { Self::Bytes { body: Bytes::copy_from_slice(s), } } } impl<B> AnyBody<B> { /// Create body from generic message body. pub fn new(body: B) -> Self { Self::Body { body } } } impl<B> AnyBody<B> where B: MessageBody + 'static, { /// Converts a [`MessageBody`] type into the best possible representation. /// /// Checks size for `None` and tries to convert to `Bytes`. Otherwise, uses the `Body` variant. pub fn from_message_body(body: B) -> Self where B: MessageBody, { if matches!(body.size(), BodySize::None) { return Self::None; } match body.try_into_bytes() { Ok(body) => Self::Bytes { body }, Err(body) => Self::new(body), } } pub fn into_boxed(self) -> AnyBody { match self { Self::None => AnyBody::None, Self::Bytes { body } => AnyBody::Bytes { body }, Self::Body { body } => AnyBody::new_boxed(body), } } } impl<B> MessageBody for AnyBody<B> where B: MessageBody, { type Error = crate::BoxError; fn size(&self) -> BodySize { match self { AnyBody::None => BodySize::None, AnyBody::Bytes { ref body } => BodySize::Sized(body.len() as u64), AnyBody::Body { ref body } => body.size(), } } fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { match self.project() { AnyBodyProj::None => Poll::Ready(None), AnyBodyProj::Bytes { body } => { let len = body.len(); if len == 0 { Poll::Ready(None) } else { Poll::Ready(Some(Ok(mem::take(body)))) } } AnyBodyProj::Body { body } => body.poll_next(cx).map_err(|err| err.into()), } } } impl PartialEq for AnyBody { fn eq(&self, other: &AnyBody) -> bool { match self { AnyBody::None => matches!(*other, AnyBody::None), AnyBody::Bytes { body } => match other { AnyBody::Bytes { body: b2 } => body == b2, _ => false, }, AnyBody::Body { .. } => false, } } } impl<S: fmt::Debug> fmt::Debug for AnyBody<S> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { AnyBody::None => write!(f, "AnyBody::None"), AnyBody::Bytes { ref body } => write!(f, "AnyBody::Bytes({:?})", body), AnyBody::Body { ref body } => write!(f, "AnyBody::Message({:?})", body), } } } #[cfg(test)] mod tests { use std::marker::PhantomPinned; use static_assertions::{assert_impl_all, assert_not_impl_any}; use super::*; #[allow(dead_code)] struct PinType(PhantomPinned); impl MessageBody for PinType { type Error = crate::BoxError; fn size(&self) -> BodySize { unimplemented!() } fn poll_next( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { unimplemented!() } } assert_impl_all!(AnyBody<()>: Send, Sync, Unpin, fmt::Debug, MessageBody); assert_impl_all!(AnyBody<AnyBody<()>>: Send, Sync, Unpin, fmt::Debug, MessageBody); assert_impl_all!(AnyBody<Bytes>: Send, Sync, Unpin, fmt::Debug, MessageBody); assert_impl_all!(AnyBody: Unpin, fmt::Debug, MessageBody); assert_impl_all!(AnyBody<PinType>: Send, Sync, MessageBody); assert_not_impl_any!(AnyBody: Send, Sync); assert_not_impl_any!(AnyBody<PinType>: Unpin); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/ws.rs
awc/src/ws.rs
//! Websockets client //! //! Type definitions required to use [`awc::Client`](super::Client) as a WebSocket client. //! //! # Examples //! //! ```no_run //! use awc::{Client, ws}; //! use futures_util::{SinkExt as _, StreamExt as _}; //! //! #[actix_rt::main] //! async fn main() { //! let (_resp, mut connection) = Client::new() //! .ws("ws://echo.websocket.org") //! .connect() //! .await //! .unwrap(); //! //! connection //! .send(ws::Message::Text("Echo".into())) //! .await //! .unwrap(); //! let response = connection.next().await.unwrap().unwrap(); //! //! assert_eq!(response, ws::Frame::Text("Echo".as_bytes().into())); //! } //! ``` use std::{fmt, net::SocketAddr, str}; use actix_codec::Framed; pub use actix_http::ws::{CloseCode, CloseReason, Codec, Frame, Message}; use actix_http::{ws, Payload, RequestHead}; use actix_rt::time::timeout; use actix_service::Service as _; use base64::prelude::*; #[cfg(feature = "cookies")] use crate::cookie::{Cookie, CookieJar}; use crate::{ client::ClientConfig, connect::{BoxedSocket, ConnectRequest}, error::{HttpError, InvalidUrl, SendRequestError, WsClientError}, http::{ header::{self, HeaderName, HeaderValue, TryIntoHeaderValue, AUTHORIZATION}, ConnectionType, Method, StatusCode, Uri, Version, }, ClientResponse, }; /// WebSocket connection. pub struct WebsocketsRequest { pub(crate) head: RequestHead, err: Option<HttpError>, origin: Option<HeaderValue>, protocols: Option<String>, addr: Option<SocketAddr>, max_size: usize, server_mode: bool, config: ClientConfig, #[cfg(feature = "cookies")] cookies: Option<CookieJar>, } impl WebsocketsRequest { /// Create new WebSocket connection. pub(crate) fn new<U>(uri: U, config: ClientConfig) -> Self where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { let mut err = None; #[allow(clippy::field_reassign_with_default)] let mut head = { let mut head = RequestHead::default(); head.method = Method::GET; head.version = Version::HTTP_11; head }; match Uri::try_from(uri) { Ok(uri) => head.uri = uri, Err(error) => err = Some(error.into()), } WebsocketsRequest { head, err, config, addr: None, origin: None, protocols: None, max_size: 65_536, server_mode: false, #[cfg(feature = "cookies")] cookies: None, } } /// Set socket address of the server. /// /// This address is used for connection. If address is not /// provided url's host name get resolved. pub fn address(mut self, addr: SocketAddr) -> Self { self.addr = Some(addr); self } /// Set supported WebSocket protocols pub fn protocols<U, V>(mut self, protos: U) -> Self where U: IntoIterator<Item = V>, V: AsRef<str>, { let mut protos = protos .into_iter() .fold(String::new(), |acc, s| acc + s.as_ref() + ","); protos.pop(); self.protocols = Some(protos); self } /// Set a cookie #[cfg(feature = "cookies")] pub fn cookie(mut self, cookie: Cookie<'_>) -> Self { if self.cookies.is_none() { let mut jar = CookieJar::new(); jar.add(cookie.into_owned()); self.cookies = Some(jar) } else { self.cookies.as_mut().unwrap().add(cookie.into_owned()); } self } /// Set request Origin pub fn origin<V, E>(mut self, origin: V) -> Self where HeaderValue: TryFrom<V, Error = E>, HttpError: From<E>, { match HeaderValue::try_from(origin) { Ok(value) => self.origin = Some(value), Err(err) => self.err = Some(err.into()), } self } /// Set max frame size /// /// By default max size is set to 64kB pub fn max_frame_size(mut self, size: usize) -> Self { self.max_size = size; self } /// Disable payload masking. By default ws client masks frame payload. pub fn server_mode(mut self) -> Self { self.server_mode = true; self } /// Append a header. /// /// Header gets appended to existing header. /// To override header use `set_header()` method. pub fn header<K, V>(mut self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<HttpError>, V: TryIntoHeaderValue, { match HeaderName::try_from(key) { Ok(key) => match value.try_into_value() { Ok(value) => { self.head.headers.append(key, value); } Err(err) => self.err = Some(err.into()), }, Err(err) => self.err = Some(err.into()), } self } /// Insert a header, replaces existing header. pub fn set_header<K, V>(mut self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<HttpError>, V: TryIntoHeaderValue, { match HeaderName::try_from(key) { Ok(key) => match value.try_into_value() { Ok(value) => { self.head.headers.insert(key, value); } Err(err) => self.err = Some(err.into()), }, Err(err) => self.err = Some(err.into()), } self } /// Insert a header only if it is not yet set. pub fn set_header_if_none<K, V>(mut self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<HttpError>, V: TryIntoHeaderValue, { match HeaderName::try_from(key) { Ok(key) => { if !self.head.headers.contains_key(&key) { match value.try_into_value() { Ok(value) => { self.head.headers.insert(key, value); } Err(err) => self.err = Some(err.into()), } } } Err(err) => self.err = Some(err.into()), } self } /// Set HTTP basic authorization header pub fn basic_auth<U>(self, username: U, password: Option<&str>) -> Self where U: fmt::Display, { let auth = match password { Some(password) => format!("{}:{}", username, password), None => format!("{}:", username), }; self.header( AUTHORIZATION, format!("Basic {}", BASE64_STANDARD.encode(auth)), ) } /// Set HTTP bearer authentication header pub fn bearer_auth<T>(self, token: T) -> Self where T: fmt::Display, { self.header(AUTHORIZATION, format!("Bearer {}", token)) } /// Complete request construction and connect to a WebSocket server. pub async fn connect( mut self, ) -> Result<(ClientResponse, Framed<BoxedSocket, Codec>), WsClientError> { if let Some(err) = self.err.take() { return Err(err.into()); } // validate URI let uri = &self.head.uri; if uri.host().is_none() { return Err(InvalidUrl::MissingHost.into()); } else if uri.scheme().is_none() { return Err(InvalidUrl::MissingScheme.into()); } else if let Some(scheme) = uri.scheme() { match scheme.as_str() { "http" | "ws" | "https" | "wss" => {} _ => return Err(InvalidUrl::UnknownScheme.into()), } } else { return Err(InvalidUrl::UnknownScheme.into()); } if !self.head.headers.contains_key(header::HOST) { let hostname = uri.host().unwrap(); let port = uri.port(); self.head.headers.insert( header::HOST, HeaderValue::from_str(&Host { hostname, port }.to_string()).unwrap(), ); } // set cookies #[cfg(feature = "cookies")] if let Some(ref mut jar) = self.cookies { let cookie: String = jar .delta() // ensure only name=value is written to cookie header .map(|c| c.stripped().encoded().to_string()) .collect::<Vec<_>>() .join("; "); if !cookie.is_empty() { self.head .headers .insert(header::COOKIE, HeaderValue::from_str(&cookie).unwrap()); } } // origin if let Some(origin) = self.origin.take() { self.head.headers.insert(header::ORIGIN, origin); } self.head.set_connection_type(ConnectionType::Upgrade); #[allow(clippy::declare_interior_mutable_const)] const HV_WEBSOCKET: HeaderValue = HeaderValue::from_static("websocket"); self.head.headers.insert(header::UPGRADE, HV_WEBSOCKET); #[allow(clippy::declare_interior_mutable_const)] const HV_THIRTEEN: HeaderValue = HeaderValue::from_static("13"); self.head .headers .insert(header::SEC_WEBSOCKET_VERSION, HV_THIRTEEN); if let Some(protocols) = self.protocols.take() { self.head.headers.insert( header::SEC_WEBSOCKET_PROTOCOL, HeaderValue::try_from(protocols.as_str()).unwrap(), ); } // Generate a random key for the `Sec-WebSocket-Key` header which is a base64-encoded // (see RFC 4648 §4) value that, when decoded, is 16 bytes in length (RFC 6455 §1.3). let sec_key = rand::random::<[u8; 16]>(); let key = BASE64_STANDARD.encode(sec_key); self.head.headers.insert( header::SEC_WEBSOCKET_KEY, HeaderValue::try_from(key.as_str()).unwrap(), ); let head = self.head; let max_size = self.max_size; let server_mode = self.server_mode; let req = ConnectRequest::Tunnel(head, self.addr); let fut = self.config.connector.call(req); // set request timeout let res = if let Some(to) = self.config.timeout { timeout(to, fut) .await .map_err(|_| SendRequestError::Timeout)?? } else { fut.await? }; let (head, framed) = res.into_tunnel_response(); // verify response if head.status != StatusCode::SWITCHING_PROTOCOLS { return Err(WsClientError::InvalidResponseStatus(head.status)); } // check for "UPGRADE" to WebSocket header let has_hdr = if let Some(hdr) = head.headers.get(&header::UPGRADE) { if let Ok(s) = hdr.to_str() { s.to_ascii_lowercase().contains("websocket") } else { false } } else { false }; if !has_hdr { log::trace!("Invalid upgrade header"); return Err(WsClientError::InvalidUpgradeHeader); } // Check for "CONNECTION" header if let Some(conn) = head.headers.get(&header::CONNECTION) { if let Ok(s) = conn.to_str() { if !s.to_ascii_lowercase().contains("upgrade") { log::trace!("Invalid connection header: {}", s); return Err(WsClientError::InvalidConnectionHeader(conn.clone())); } } else { log::trace!("Invalid connection header: {:?}", conn); return Err(WsClientError::InvalidConnectionHeader(conn.clone())); } } else { log::trace!("Missing connection header"); return Err(WsClientError::MissingConnectionHeader); } if let Some(hdr_key) = head.headers.get(&header::SEC_WEBSOCKET_ACCEPT) { let encoded = ws::hash_key(key.as_ref()); if hdr_key.as_bytes() != encoded { log::trace!( "Invalid challenge response: expected: {:?} received: {:?}", &encoded, key ); return Err(WsClientError::InvalidChallengeResponse( encoded, hdr_key.clone(), )); } } else { log::trace!("Missing SEC-WEBSOCKET-ACCEPT header"); return Err(WsClientError::MissingWebSocketAcceptHeader); }; // response and ws framed Ok(( ClientResponse::new(head, Payload::None), framed.into_map_codec(|_| { if server_mode { ws::Codec::new().max_size(max_size) } else { ws::Codec::new().max_size(max_size).client_mode() } }), )) } } impl fmt::Debug for WebsocketsRequest { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "\nWebsocketsRequest {}:{}", self.head.method, self.head.uri )?; writeln!(f, " headers:")?; for (key, val) in self.head.headers.iter() { writeln!(f, " {:?}: {:?}", key, val)?; } Ok(()) } } /// Formatter for host (hostname+port) header values. struct Host<'a> { hostname: &'a str, port: Option<http::uri::Port<&'a str>>, } impl fmt::Display for Host<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str(self.hostname)?; if let Some(port) = &self.port { f.write_str(":")?; f.write_str(port.as_str())?; } Ok(()) } } #[cfg(test)] mod tests { use super::*; use crate::Client; #[actix_rt::test] async fn test_debug() { let request = Client::new().ws("/").header("x-test", "111"); let repr = format!("{:?}", request); assert!(repr.contains("WebsocketsRequest")); assert!(repr.contains("x-test")); } #[actix_rt::test] async fn test_header_override() { let req = Client::builder() .add_default_header((header::CONTENT_TYPE, "111")) .finish() .ws("/") .set_header(header::CONTENT_TYPE, "222"); assert_eq!( req.head .headers .get(header::CONTENT_TYPE) .unwrap() .to_str() .unwrap(), "222" ); } #[actix_rt::test] async fn basic_auth() { let req = Client::new() .ws("/") .basic_auth("username", Some("password")); assert_eq!( req.head .headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" ); let req = Client::new().ws("/").basic_auth("username", None); assert_eq!( req.head .headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Basic dXNlcm5hbWU6" ); } #[actix_rt::test] async fn bearer_auth() { let req = Client::new().ws("/").bearer_auth("someS3cr3tAutht0k3n"); assert_eq!( req.head .headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Bearer someS3cr3tAutht0k3n" ); #[allow(clippy::let_underscore_future)] let _ = req.connect(); } #[actix_rt::test] async fn basics() { let req = Client::new() .ws("http://localhost/") .origin("test-origin") .max_frame_size(100) .server_mode() .protocols(["v1", "v2"]) .set_header_if_none(header::CONTENT_TYPE, "json") .set_header_if_none(header::CONTENT_TYPE, "text") .cookie(Cookie::build("cookie1", "value1").finish()); assert_eq!( req.origin.as_ref().unwrap().to_str().unwrap(), "test-origin" ); assert_eq!(req.max_size, 100); assert!(req.server_mode); assert_eq!(req.protocols, Some("v1,v2".to_string())); assert_eq!( req.head.headers.get(header::CONTENT_TYPE).unwrap(), header::HeaderValue::from_static("json") ); let _ = req.connect().await; assert!(Client::new().ws("/").connect().await.is_err()); assert!(Client::new().ws("http:///test").connect().await.is_err()); assert!(Client::new().ws("hmm://test.com/").connect().await.is_err()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/request.rs
awc/src/request.rs
use std::{fmt, net, rc::Rc, time::Duration}; use actix_http::{ body::MessageBody, error::HttpError, header::{self, HeaderMap, HeaderValue, TryIntoHeaderPair}, ConnectionType, Method, RequestHead, Uri, Version, }; use base64::prelude::*; use bytes::Bytes; use futures_core::Stream; use serde::Serialize; #[cfg(feature = "cookies")] use crate::cookie::{Cookie, CookieJar}; use crate::{ client::ClientConfig, error::{FreezeRequestError, InvalidUrl}, frozen::FrozenClientRequest, sender::{PrepForSendingError, RequestSender, SendClientRequest}, BoxError, }; /// An HTTP Client request builder /// /// This type can be used to construct an instance of `ClientRequest` through a /// builder-like pattern. /// /// ```no_run /// # #[actix_rt::main] /// # async fn main() { /// let response = awc::Client::new() /// .get("http://www.rust-lang.org") // <- Create request builder /// .insert_header(("User-Agent", "Actix-web")) /// .send() // <- Send HTTP request /// .await; /// /// response.and_then(|response| { // <- server HTTP response /// println!("Response: {:?}", response); /// Ok(()) /// }); /// # } /// ``` pub struct ClientRequest { pub(crate) head: RequestHead, err: Option<HttpError>, addr: Option<net::SocketAddr>, response_decompress: bool, timeout: Option<Duration>, config: ClientConfig, #[cfg(feature = "cookies")] cookies: Option<CookieJar>, } impl ClientRequest { /// Create new client request builder. pub(crate) fn new<U>(method: Method, uri: U, config: ClientConfig) -> Self where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { ClientRequest { config, head: RequestHead::default(), err: None, addr: None, #[cfg(feature = "cookies")] cookies: None, timeout: None, response_decompress: true, } .method(method) .uri(uri) } /// Set HTTP URI of request. #[inline] pub fn uri<U>(mut self, uri: U) -> Self where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { match Uri::try_from(uri) { Ok(uri) => self.head.uri = uri, Err(err) => self.err = Some(err.into()), } self } /// Get HTTP URI of request. pub fn get_uri(&self) -> &Uri { &self.head.uri } /// Set socket address of the server. /// /// This address is used for connection. If address is not /// provided url's host name get resolved. pub fn address(mut self, addr: net::SocketAddr) -> Self { self.addr = Some(addr); self } /// Set HTTP method of this request. #[inline] pub fn method(mut self, method: Method) -> Self { self.head.method = method; self } /// Get HTTP method of this request pub fn get_method(&self) -> &Method { &self.head.method } /// Set HTTP version of this request. /// /// By default requests's HTTP version depends on network stream #[doc(hidden)] #[inline] pub fn version(mut self, version: Version) -> Self { self.head.version = version; self } /// Get HTTP version of this request. pub fn get_version(&self) -> &Version { &self.head.version } /// Get peer address of this request. pub fn get_peer_addr(&self) -> &Option<net::SocketAddr> { &self.head.peer_addr } /// Returns request's headers. #[inline] pub fn headers(&self) -> &HeaderMap { &self.head.headers } /// Returns request's mutable headers. #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.head.headers } /// Insert a header, replacing any that were set with an equivalent field name. pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self { match header.try_into_pair() { Ok((key, value)) => { self.head.headers.insert(key, value); } Err(err) => self.err = Some(err.into()), }; self } /// Insert a header only if it is not yet set. pub fn insert_header_if_none(mut self, header: impl TryIntoHeaderPair) -> Self { match header.try_into_pair() { Ok((key, value)) => { if !self.head.headers.contains_key(&key) { self.head.headers.insert(key, value); } } Err(err) => self.err = Some(err.into()), }; self } /// Append a header, keeping any that were set with an equivalent field name. /// /// ```no_run /// use awc::{http::header, Client}; /// /// Client::new() /// .get("http://www.rust-lang.org") /// .insert_header(("X-TEST", "value")) /// .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)); /// ``` pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self { match header.try_into_pair() { Ok((key, value)) => self.head.headers.append(key, value), Err(err) => self.err = Some(err.into()), }; self } /// Send headers in `Camel-Case` form. #[inline] pub fn camel_case(mut self) -> Self { self.head.set_camel_case_headers(true); self } /// Force close connection instead of returning it back to connections pool. /// This setting affect only HTTP/1 connections. #[inline] pub fn force_close(mut self) -> Self { self.head.set_connection_type(ConnectionType::Close); self } /// Set request's content type #[inline] pub fn content_type<V>(mut self, value: V) -> Self where HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<HttpError>, { match HeaderValue::try_from(value) { Ok(value) => { self.head.headers.insert(header::CONTENT_TYPE, value); } Err(err) => self.err = Some(err.into()), } self } /// Set content length #[inline] pub fn content_length(self, len: u64) -> Self { let mut buf = itoa::Buffer::new(); self.insert_header((header::CONTENT_LENGTH, buf.format(len))) } /// Set HTTP basic authorization header. /// /// If no password is needed, just provide an empty string. pub fn basic_auth(self, username: impl fmt::Display, password: impl fmt::Display) -> Self { let auth = format!("{}:{}", username, password); self.insert_header(( header::AUTHORIZATION, format!("Basic {}", BASE64_STANDARD.encode(auth)), )) } /// Set HTTP bearer authentication header pub fn bearer_auth(self, token: impl fmt::Display) -> Self { self.insert_header((header::AUTHORIZATION, format!("Bearer {}", token))) } /// Set a cookie /// /// ```no_run /// use awc::{cookie::Cookie, Client}; /// /// # #[actix_rt::main] /// # async fn main() { /// let res = Client::new().get("https://httpbin.org/cookies") /// .cookie(Cookie::new("name", "value")) /// .send() /// .await; /// /// println!("Response: {:?}", res); /// # } /// ``` #[cfg(feature = "cookies")] pub fn cookie(mut self, cookie: Cookie<'_>) -> Self { if self.cookies.is_none() { let mut jar = CookieJar::new(); jar.add(cookie.into_owned()); self.cookies = Some(jar) } else { self.cookies.as_mut().unwrap().add(cookie.into_owned()); } self } /// Disable automatic decompress of response's body pub fn no_decompress(mut self) -> Self { self.response_decompress = false; self } /// Set request timeout. Overrides client wide timeout setting. /// /// Request timeout is the total time before a response must be received. /// Default value is 5 seconds. pub fn timeout(mut self, timeout: Duration) -> Self { self.timeout = Some(timeout); self } /// Sets the query part of the request pub fn query<T: Serialize>(mut self, query: &T) -> Result<Self, serde_urlencoded::ser::Error> { let mut parts = self.head.uri.clone().into_parts(); if let Some(path_and_query) = parts.path_and_query { let query = serde_urlencoded::to_string(query)?; let path = path_and_query.path(); parts.path_and_query = format!("{}?{}", path, query).parse().ok(); match Uri::from_parts(parts) { Ok(uri) => self.head.uri = uri, Err(err) => self.err = Some(err.into()), } } Ok(self) } /// Freeze request builder and construct `FrozenClientRequest`, /// which could be used for sending same request multiple times. pub fn freeze(self) -> Result<FrozenClientRequest, FreezeRequestError> { let slf = self.prep_for_sending()?; let request = FrozenClientRequest { head: Rc::new(slf.head), addr: slf.addr, response_decompress: slf.response_decompress, timeout: slf.timeout, config: slf.config, }; Ok(request) } /// Complete request construction and send body. pub fn send_body<B>(self, body: B) -> SendClientRequest where B: MessageBody + 'static, { let slf = match self.prep_for_sending() { Ok(slf) => slf, Err(err) => return err.into(), }; RequestSender::Owned(slf.head).send_body( slf.addr, slf.response_decompress, slf.timeout, &slf.config, body, ) } /// Set a JSON body and generate `ClientRequest` pub fn send_json<T: Serialize>(self, value: &T) -> SendClientRequest { let slf = match self.prep_for_sending() { Ok(slf) => slf, Err(err) => return err.into(), }; RequestSender::Owned(slf.head).send_json( slf.addr, slf.response_decompress, slf.timeout, &slf.config, value, ) } /// Set a urlencoded body and generate `ClientRequest` /// /// `ClientRequestBuilder` can not be used after this call. pub fn send_form<T: Serialize>(self, value: &T) -> SendClientRequest { let slf = match self.prep_for_sending() { Ok(slf) => slf, Err(err) => return err.into(), }; RequestSender::Owned(slf.head).send_form( slf.addr, slf.response_decompress, slf.timeout, &slf.config, value, ) } /// Set an streaming body and generate `ClientRequest`. pub fn send_stream<S, E>(self, stream: S) -> SendClientRequest where S: Stream<Item = Result<Bytes, E>> + 'static, E: Into<BoxError> + 'static, { let slf = match self.prep_for_sending() { Ok(slf) => slf, Err(err) => return err.into(), }; RequestSender::Owned(slf.head).send_stream( slf.addr, slf.response_decompress, slf.timeout, &slf.config, stream, ) } /// Set an empty body and generate `ClientRequest`. pub fn send(self) -> SendClientRequest { let slf = match self.prep_for_sending() { Ok(slf) => slf, Err(err) => return err.into(), }; RequestSender::Owned(slf.head).send( slf.addr, slf.response_decompress, slf.timeout, &slf.config, ) } // allow unused mut when cookies feature is disabled fn prep_for_sending(#[allow(unused_mut)] mut self) -> Result<Self, PrepForSendingError> { if let Some(err) = self.err { return Err(err.into()); } // validate uri let uri = &self.head.uri; if uri.host().is_none() { return Err(InvalidUrl::MissingHost.into()); } else if uri.scheme().is_none() { return Err(InvalidUrl::MissingScheme.into()); } else if let Some(scheme) = uri.scheme() { match scheme.as_str() { "http" | "ws" | "https" | "wss" => {} _ => return Err(InvalidUrl::UnknownScheme.into()), } } else { return Err(InvalidUrl::UnknownScheme.into()); } // set cookies #[cfg(feature = "cookies")] if let Some(ref mut jar) = self.cookies { let cookie: String = jar .delta() // ensure only name=value is written to cookie header .map(|c| c.stripped().encoded().to_string()) .collect::<Vec<_>>() .join("; "); if !cookie.is_empty() { self.head .headers .insert(header::COOKIE, HeaderValue::from_str(&cookie).unwrap()); } } let mut slf = self; // Set Accept-Encoding HTTP header depending on enabled feature. // If decompress is not ask, then we are not able to find which encoding is // supported, so we cannot guess Accept-Encoding HTTP header. if slf.response_decompress { // Set Accept-Encoding with compression algorithm awc is built with. #[allow(clippy::vec_init_then_push)] #[cfg(feature = "__compress")] let accept_encoding = { let mut encoding = vec![]; #[cfg(feature = "compress-brotli")] { encoding.push("br"); } #[cfg(feature = "compress-gzip")] { encoding.push("gzip"); encoding.push("deflate"); } #[cfg(feature = "compress-zstd")] encoding.push("zstd"); assert!( !encoding.is_empty(), "encoding can not be empty unless __compress feature has been explicitly enabled" ); encoding.join(", ") }; // Otherwise tell the server, we do not support any compression algorithm. // So we clearly indicate that we do want identity encoding. #[cfg(not(feature = "__compress"))] let accept_encoding = "identity"; slf = slf.insert_header_if_none((header::ACCEPT_ENCODING, accept_encoding)); } Ok(slf) } } impl fmt::Debug for ClientRequest { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "\nClientRequest {:?} {} {}", self.head.version, self.head.method, self.head.uri )?; writeln!(f, " headers:")?; for (key, val) in self.head.headers.iter() { writeln!(f, " {:?}: {:?}", key, val)?; } Ok(()) } } #[cfg(test)] mod tests { use std::time::SystemTime; use actix_http::header::HttpDate; use super::*; use crate::Client; #[actix_rt::test] async fn test_debug() { let request = Client::new().get("/").append_header(("x-test", "111")); let repr = format!("{:?}", request); assert!(repr.contains("ClientRequest")); assert!(repr.contains("x-test")); } #[actix_rt::test] async fn test_basics() { let req = Client::new() .put("/") .version(Version::HTTP_2) .insert_header((header::DATE, HttpDate::from(SystemTime::now()))) .content_type("plain/text") .append_header((header::SERVER, "awc")); let req = if let Some(val) = Some("server") { req.append_header((header::USER_AGENT, val)) } else { req }; let req = if let Some(_val) = Option::<&str>::None { req.append_header((header::ALLOW, "1")) } else { req }; let mut req = req.content_length(100); assert!(req.headers().contains_key(header::CONTENT_TYPE)); assert!(req.headers().contains_key(header::DATE)); assert!(req.headers().contains_key(header::SERVER)); assert!(req.headers().contains_key(header::USER_AGENT)); assert!(!req.headers().contains_key(header::ALLOW)); assert!(!req.headers().contains_key(header::EXPECT)); assert_eq!(req.head.version, Version::HTTP_2); let _ = req.headers_mut(); #[allow(clippy::let_underscore_future)] let _ = req.send_body(""); } #[actix_rt::test] async fn test_client_header() { let req = Client::builder() .add_default_header((header::CONTENT_TYPE, "111")) .finish() .get("/"); assert_eq!( req.head .headers .get(header::CONTENT_TYPE) .unwrap() .to_str() .unwrap(), "111" ); } #[actix_rt::test] async fn test_client_header_override() { let req = Client::builder() .add_default_header((header::CONTENT_TYPE, "111")) .finish() .get("/") .insert_header((header::CONTENT_TYPE, "222")); assert_eq!( req.head .headers .get(header::CONTENT_TYPE) .unwrap() .to_str() .unwrap(), "222" ); } #[actix_rt::test] async fn client_basic_auth() { let req = Client::new().get("/").basic_auth("username", "password"); assert_eq!( req.head .headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Basic dXNlcm5hbWU6cGFzc3dvcmQ=" ); let req = Client::new().get("/").basic_auth("username", ""); assert_eq!( req.head .headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Basic dXNlcm5hbWU6" ); } #[actix_rt::test] async fn client_bearer_auth() { let req = Client::new().get("/").bearer_auth("someS3cr3tAutht0k3n"); assert_eq!( req.head .headers .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap(), "Bearer someS3cr3tAutht0k3n" ); } #[actix_rt::test] async fn client_query() { let req = Client::new() .get("/") .query(&[("key1", "val1"), ("key2", "val2")]) .unwrap(); assert_eq!(req.get_uri().query().unwrap(), "key1=val1&key2=val2"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/middleware/redirect.rs
awc/src/middleware/redirect.rs
use std::{ future::Future, net::SocketAddr, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_http::{header, Method, RequestHead, RequestHeadType, StatusCode, Uri}; use actix_service::Service; use bytes::Bytes; use futures_core::ready; use super::Transform; use crate::{ any_body::AnyBody, client::{InvalidUrl, SendRequestError}, connect::{ConnectRequest, ConnectResponse}, ClientResponse, }; pub struct Redirect { max_redirect_times: u8, } impl Default for Redirect { fn default() -> Self { Self::new() } } impl Redirect { pub fn new() -> Self { Self { max_redirect_times: 10, } } pub fn max_redirect_times(mut self, times: u8) -> Self { self.max_redirect_times = times; self } } impl<S> Transform<S, ConnectRequest> for Redirect where S: Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError> + 'static, { type Transform = RedirectService<S>; fn new_transform(self, service: S) -> Self::Transform { RedirectService { max_redirect_times: self.max_redirect_times, connector: Rc::new(service), } } } pub struct RedirectService<S> { max_redirect_times: u8, connector: Rc<S>, } impl<S> Service<ConnectRequest> for RedirectService<S> where S: Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError> + 'static, { type Response = S::Response; type Error = S::Error; type Future = RedirectServiceFuture<S>; actix_service::forward_ready!(connector); fn call(&self, req: ConnectRequest) -> Self::Future { match req { ConnectRequest::Tunnel(head, addr) => { let fut = self.connector.call(ConnectRequest::Tunnel(head, addr)); RedirectServiceFuture::Tunnel { fut } } ConnectRequest::Client(head, body, addr) => { let connector = Rc::clone(&self.connector); let max_redirect_times = self.max_redirect_times; // backup the uri and method for reuse schema and authority. let (uri, method, headers) = match head { RequestHeadType::Owned(ref head) => { (head.uri.clone(), head.method.clone(), head.headers.clone()) } RequestHeadType::Rc(ref head, ..) => { (head.uri.clone(), head.method.clone(), head.headers.clone()) } }; let body_opt = match body { AnyBody::Bytes { ref body } => Some(body.clone()), _ => None, }; let fut = connector.call(ConnectRequest::Client(head, body, addr)); RedirectServiceFuture::Client { fut, max_redirect_times, uri: Some(uri), method: Some(method), headers: Some(headers), body: body_opt, addr, connector: Some(connector), } } } } } pin_project_lite::pin_project! { #[project = RedirectServiceProj] pub enum RedirectServiceFuture<S> where S: Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError>, S: 'static { Tunnel { #[pin] fut: S::Future }, Client { #[pin] fut: S::Future, max_redirect_times: u8, uri: Option<Uri>, method: Option<Method>, headers: Option<header::HeaderMap>, body: Option<Bytes>, addr: Option<SocketAddr>, connector: Option<Rc<S>>, } } } impl<S> Future for RedirectServiceFuture<S> where S: Service<ConnectRequest, Response = ConnectResponse, Error = SendRequestError> + 'static, { type Output = Result<ConnectResponse, SendRequestError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match self.as_mut().project() { RedirectServiceProj::Tunnel { fut } => fut.poll(cx), RedirectServiceProj::Client { fut, max_redirect_times, uri, method, headers, body, addr, connector, } => match ready!(fut.poll(cx))? { ConnectResponse::Client(res) => match res.head().status { StatusCode::MOVED_PERMANENTLY | StatusCode::FOUND | StatusCode::SEE_OTHER | StatusCode::TEMPORARY_REDIRECT | StatusCode::PERMANENT_REDIRECT if *max_redirect_times > 0 && res.headers().contains_key(header::LOCATION) => { let reuse_body = res.head().status == StatusCode::TEMPORARY_REDIRECT || res.head().status == StatusCode::PERMANENT_REDIRECT; let prev_uri = uri.take().unwrap(); // rebuild uri from the location header value. let next_uri = build_next_uri(&res, &prev_uri)?; // take ownership of states that could be reused let addr = addr.take(); let connector = connector.take(); // reset method let method = if reuse_body { method.take().unwrap() } else { let method = method.take().unwrap(); match method { Method::GET | Method::HEAD => method, _ => Method::GET, } }; let mut body = body.take(); let body_new = if reuse_body { // try to reuse saved body match body { Some(ref bytes) => AnyBody::Bytes { body: bytes.clone(), }, // body was a non-reusable type so send an empty body instead _ => AnyBody::empty(), } } else { body = None; // remove body since we're downgrading to a GET AnyBody::None }; let mut headers = headers.take().unwrap(); remove_sensitive_headers(&mut headers, &prev_uri, &next_uri); // use a new request head. let mut head = RequestHead::default(); head.uri = next_uri.clone(); head.method = method.clone(); head.headers = headers.clone(); let head = RequestHeadType::Owned(head); let mut max_redirect_times = *max_redirect_times; max_redirect_times -= 1; let fut = connector .as_ref() .unwrap() .call(ConnectRequest::Client(head, body_new, addr)); self.set(RedirectServiceFuture::Client { fut, max_redirect_times, uri: Some(next_uri), method: Some(method), headers: Some(headers), body, addr, connector, }); self.poll(cx) } _ => Poll::Ready(Ok(ConnectResponse::Client(res))), }, _ => unreachable!("ConnectRequest::Tunnel is not handled by Redirect"), }, } } } fn build_next_uri(res: &ClientResponse, prev_uri: &Uri) -> Result<Uri, SendRequestError> { // responses without this header are not processed let location = res.headers().get(header::LOCATION).unwrap(); // try to parse the location and resolve to a full URI but fall back to default if it fails let uri = Uri::try_from(location.as_bytes()).unwrap_or_else(|_| Uri::default()); let uri = if uri.scheme().is_none() || uri.authority().is_none() { let builder = Uri::builder() .scheme(prev_uri.scheme().cloned().unwrap()) .authority(prev_uri.authority().cloned().unwrap()); // scheme-relative address if location.as_bytes().starts_with(b"//") { let scheme = prev_uri.scheme_str().unwrap(); let mut full_url: Vec<u8> = scheme.as_bytes().to_vec(); full_url.push(b':'); full_url.extend(location.as_bytes()); return Uri::try_from(full_url) .map_err(|_| SendRequestError::Url(InvalidUrl::MissingScheme)); } // when scheme or authority is missing treat the location value as path and query // recover error where location does not have leading slash let path = if location.as_bytes().starts_with(b"/") { location.as_bytes().to_owned() } else { [b"/", location.as_bytes()].concat() }; builder .path_and_query(path) .build() .map_err(|err| SendRequestError::Url(InvalidUrl::HttpError(err)))? } else { uri }; Ok(uri) } fn remove_sensitive_headers(headers: &mut header::HeaderMap, prev_uri: &Uri, next_uri: &Uri) { if next_uri.host() != prev_uri.host() || next_uri.port() != prev_uri.port() || next_uri.scheme() != prev_uri.scheme() { headers.remove(header::COOKIE); headers.remove(header::AUTHORIZATION); headers.remove(header::PROXY_AUTHORIZATION); } } #[cfg(test)] mod tests { use std::str::FromStr; use actix_web::{web, App, Error, HttpRequest, HttpResponse}; use super::*; use crate::{http::header::HeaderValue, ClientBuilder}; #[actix_rt::test] async fn basic_redirect() { let client = ClientBuilder::new() .disable_redirects() .wrap(Redirect::new().max_redirect_times(10)) .finish(); let srv = actix_test::start(|| { App::new() .service(web::resource("/test").route(web::to(|| async { Ok::<_, Error>(HttpResponse::BadRequest()) }))) .service(web::resource("/").route(web::to(|| async { Ok::<_, Error>( HttpResponse::Found() .append_header(("location", "/test")) .finish(), ) }))) }); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status().as_u16(), 400); } #[actix_rt::test] async fn redirect_relative_without_leading_slash() { let client = ClientBuilder::new().finish(); let srv = actix_test::start(|| { App::new() .service(web::resource("/").route(web::to(|| async { HttpResponse::Found() .insert_header(("location", "abc/")) .finish() }))) .service( web::resource("/abc/") .route(web::to(|| async { HttpResponse::Accepted().finish() })), ) }); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status(), StatusCode::ACCEPTED); } #[actix_rt::test] async fn redirect_without_location() { let client = ClientBuilder::new() .disable_redirects() .wrap(Redirect::new().max_redirect_times(10)) .finish(); let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|| async { Ok::<_, Error>(HttpResponse::Found().finish()) }))) }); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status(), StatusCode::FOUND); } #[actix_rt::test] async fn test_redirect_limit() { let client = ClientBuilder::new() .disable_redirects() .wrap(Redirect::new().max_redirect_times(1)) .connector(crate::Connector::new()) .finish(); let srv = actix_test::start(|| { App::new() .service(web::resource("/").route(web::to(|| async { Ok::<_, Error>( HttpResponse::Found() .insert_header(("location", "/test")) .finish(), ) }))) .service(web::resource("/test").route(web::to(|| async { Ok::<_, Error>( HttpResponse::Found() .insert_header(("location", "/test2")) .finish(), ) }))) .service(web::resource("/test2").route(web::to(|| async { Ok::<_, Error>(HttpResponse::BadRequest()) }))) }); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status(), StatusCode::FOUND); assert_eq!( res.headers() .get(header::LOCATION) .unwrap() .to_str() .unwrap(), "/test2" ); } #[actix_rt::test] async fn test_redirect_status_kind_307_308() { let srv = actix_test::start(|| { async fn root() -> HttpResponse { HttpResponse::TemporaryRedirect() .append_header(("location", "/test")) .finish() } async fn test(req: HttpRequest, body: Bytes) -> HttpResponse { if req.method() == Method::POST && !body.is_empty() { HttpResponse::Ok().finish() } else { HttpResponse::InternalServerError().finish() } } App::new() .service(web::resource("/").route(web::to(root))) .service(web::resource("/test").route(web::to(test))) }); let res = srv.post("/").send_body("Hello").await.unwrap(); assert_eq!(res.status().as_u16(), 200); } #[actix_rt::test] async fn test_redirect_status_kind_301_302_303() { let srv = actix_test::start(|| { async fn root() -> HttpResponse { HttpResponse::Found() .append_header(("location", "/test")) .finish() } async fn test(req: HttpRequest, body: Bytes) -> HttpResponse { if (req.method() == Method::GET || req.method() == Method::HEAD) && body.is_empty() { HttpResponse::Ok().finish() } else { HttpResponse::InternalServerError().finish() } } App::new() .service(web::resource("/").route(web::to(root))) .service(web::resource("/test").route(web::to(test))) }); let res = srv.post("/").send_body("Hello").await.unwrap(); assert_eq!(res.status().as_u16(), 200); let res = srv.post("/").send().await.unwrap(); assert_eq!(res.status().as_u16(), 200); } #[actix_rt::test] async fn test_redirect_headers() { let srv = actix_test::start(|| { async fn root(req: HttpRequest) -> HttpResponse { if req .headers() .get("custom") .unwrap_or(&HeaderValue::from_str("").unwrap()) == "value" { HttpResponse::Found() .append_header(("location", "/test")) .finish() } else { HttpResponse::InternalServerError().finish() } } async fn test(req: HttpRequest) -> HttpResponse { if req .headers() .get("custom") .unwrap_or(&HeaderValue::from_str("").unwrap()) == "value" { HttpResponse::Ok().finish() } else { HttpResponse::InternalServerError().finish() } } App::new() .service(web::resource("/").route(web::to(root))) .service(web::resource("/test").route(web::to(test))) }); let client = ClientBuilder::new() .add_default_header(("custom", "value")) .disable_redirects() .finish(); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status().as_u16(), 302); let client = ClientBuilder::new() .add_default_header(("custom", "value")) .finish(); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status().as_u16(), 200); let client = ClientBuilder::new().finish(); let res = client .get(srv.url("/")) .insert_header(("custom", "value")) .send() .await .unwrap(); assert_eq!(res.status().as_u16(), 200); } #[actix_rt::test] async fn test_redirect_cross_origin_headers() { // defining two services to have two different origins let srv2 = actix_test::start(|| { async fn root(req: HttpRequest) -> HttpResponse { if req.headers().get(header::AUTHORIZATION).is_none() { HttpResponse::Ok().finish() } else { HttpResponse::InternalServerError().finish() } } App::new().service(web::resource("/").route(web::to(root))) }); let srv2_port: u16 = srv2.addr().port(); let srv1 = actix_test::start(move || { async fn root(req: HttpRequest) -> HttpResponse { let port = *req.app_data::<u16>().unwrap(); if req.headers().get(header::AUTHORIZATION).is_some() { HttpResponse::Found() .append_header(("location", format!("http://localhost:{}/", port).as_str())) .finish() } else { HttpResponse::InternalServerError().finish() } } async fn test1(req: HttpRequest) -> HttpResponse { if req.headers().get(header::AUTHORIZATION).is_some() { HttpResponse::Found() .append_header(("location", "/test2")) .finish() } else { HttpResponse::InternalServerError().finish() } } async fn test2(req: HttpRequest) -> HttpResponse { if req.headers().get(header::AUTHORIZATION).is_some() { HttpResponse::Ok().finish() } else { HttpResponse::InternalServerError().finish() } } App::new() .app_data(srv2_port) .service(web::resource("/").route(web::to(root))) .service(web::resource("/test1").route(web::to(test1))) .service(web::resource("/test2").route(web::to(test2))) }); // send a request to different origins, http://srv1/ then http://srv2/. So it should remove the header let client = ClientBuilder::new() .add_default_header((header::AUTHORIZATION, "auth_key_value")) .finish(); let res = client.get(srv1.url("/")).send().await.unwrap(); assert_eq!(res.status().as_u16(), 200); // send a request to same origin, http://srv1/test1 then http://srv1/test2. So it should NOT remove any header let res = client.get(srv1.url("/test1")).send().await.unwrap(); assert_eq!(res.status().as_u16(), 200); } #[actix_rt::test] async fn test_double_slash_redirect() { let client = ClientBuilder::new() .disable_redirects() .wrap(Redirect::new().max_redirect_times(10)) .finish(); let srv = actix_test::start(|| { App::new() .service(web::resource("/test").route(web::to(|| async { Ok::<_, Error>(HttpResponse::BadRequest()) }))) .service( web::resource("/").route(web::to(|req: HttpRequest| async move { Ok::<_, Error>( HttpResponse::Found() .append_header(( "location", format!( "//localhost:{}/test", req.app_config().local_addr().port() ) .as_str(), )) .finish(), ) })), ) }); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status().as_u16(), 400); } #[actix_rt::test] async fn test_remove_sensitive_headers() { fn gen_headers() -> header::HeaderMap { let mut headers = header::HeaderMap::new(); headers.insert(header::USER_AGENT, HeaderValue::from_str("value").unwrap()); headers.insert( header::AUTHORIZATION, HeaderValue::from_str("value").unwrap(), ); headers.insert( header::PROXY_AUTHORIZATION, HeaderValue::from_str("value").unwrap(), ); headers.insert(header::COOKIE, HeaderValue::from_str("value").unwrap()); headers } // Same origin let prev_uri = Uri::from_str("https://host/path1").unwrap(); let next_uri = Uri::from_str("https://host/path2").unwrap(); let mut headers = gen_headers(); remove_sensitive_headers(&mut headers, &prev_uri, &next_uri); assert_eq!(headers.len(), 4); // different schema let prev_uri = Uri::from_str("http://host/").unwrap(); let next_uri = Uri::from_str("https://host/").unwrap(); let mut headers = gen_headers(); remove_sensitive_headers(&mut headers, &prev_uri, &next_uri); assert_eq!(headers.len(), 1); // different host let prev_uri = Uri::from_str("https://host1/").unwrap(); let next_uri = Uri::from_str("https://host2/").unwrap(); let mut headers = gen_headers(); remove_sensitive_headers(&mut headers, &prev_uri, &next_uri); assert_eq!(headers.len(), 1); // different port let prev_uri = Uri::from_str("https://host:12/").unwrap(); let next_uri = Uri::from_str("https://host:23/").unwrap(); let mut headers = gen_headers(); remove_sensitive_headers(&mut headers, &prev_uri, &next_uri); assert_eq!(headers.len(), 1); // different everything! let prev_uri = Uri::from_str("http://host1:12/path1").unwrap(); let next_uri = Uri::from_str("https://host2:23/path2").unwrap(); let mut headers = gen_headers(); remove_sensitive_headers(&mut headers, &prev_uri, &next_uri); assert_eq!(headers.len(), 1); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/middleware/mod.rs
awc/src/middleware/mod.rs
mod redirect; use std::marker::PhantomData; use actix_service::Service; pub use self::redirect::Redirect; /// Trait for transform a type to another one. /// Both the input and output type should impl [actix_service::Service] trait. pub trait Transform<S, Req> { type Transform: Service<Req>; /// Creates and returns a new Transform component. fn new_transform(self, service: S) -> Self::Transform; } #[doc(hidden)] /// Helper struct for constructing Nested types that would call `Transform::new_transform` /// in a chain. /// /// The child field would be called first and the output `Service` type is /// passed to parent as input type. pub struct NestTransform<T1, T2, S, Req> where T1: Transform<S, Req>, T2: Transform<T1::Transform, Req>, { child: T1, parent: T2, _service: PhantomData<(S, Req)>, } impl<T1, T2, S, Req> NestTransform<T1, T2, S, Req> where T1: Transform<S, Req>, T2: Transform<T1::Transform, Req>, { pub(crate) fn new(child: T1, parent: T2) -> Self { NestTransform { child, parent, _service: PhantomData, } } } impl<T1, T2, S, Req> Transform<S, Req> for NestTransform<T1, T2, S, Req> where T1: Transform<S, Req>, T2: Transform<T1::Transform, Req>, { type Transform = T2::Transform; fn new_transform(self, service: S) -> Self::Transform { let service = self.child.new_transform(service); self.parent.new_transform(service) } } /// Dummy impl for kick start `NestTransform` type in `ClientBuilder` type impl<S, Req> Transform<S, Req> for () where S: Service<Req>, { type Transform = S; fn new_transform(self, service: S) -> Self::Transform { service } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/client/config.rs
awc/src/client/config.rs
use std::{net::IpAddr, time::Duration}; const DEFAULT_H2_CONN_WINDOW: u32 = 1024 * 1024 * 2; // 2MB const DEFAULT_H2_STREAM_WINDOW: u32 = 1024 * 1024; // 1MB /// Connector configuration #[derive(Clone)] pub(crate) struct ConnectorConfig { pub(crate) timeout: Duration, pub(crate) handshake_timeout: Duration, pub(crate) conn_lifetime: Duration, pub(crate) conn_keep_alive: Duration, pub(crate) disconnect_timeout: Option<Duration>, pub(crate) limit: usize, pub(crate) conn_window_size: u32, pub(crate) stream_window_size: u32, pub(crate) local_address: Option<IpAddr>, } impl Default for ConnectorConfig { fn default() -> Self { Self { timeout: Duration::from_secs(5), handshake_timeout: Duration::from_secs(5), conn_lifetime: Duration::from_secs(75), conn_keep_alive: Duration::from_secs(15), disconnect_timeout: Some(Duration::from_millis(3000)), limit: 100, conn_window_size: DEFAULT_H2_CONN_WINDOW, stream_window_size: DEFAULT_H2_STREAM_WINDOW, local_address: None, } } } impl ConnectorConfig { pub(crate) fn no_disconnect_timeout(&self) -> Self { let mut res = self.clone(); res.disconnect_timeout = None; res } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/client/h2proto.rs
awc/src/client/h2proto.rs
use std::future::Future; use actix_http::{ body::{BodySize, MessageBody}, header::HeaderMap, Payload, RequestHeadType, ResponseHead, }; use actix_utils::future::poll_fn; use bytes::Bytes; use h2::{ client::{Builder, Connection, SendRequest}, SendStream, }; use http::{ header::{HeaderValue, CONNECTION, CONTENT_LENGTH, HOST, TRANSFER_ENCODING}, request::Request, Method, Version, }; use log::trace; use super::{ config::ConnectorConfig, connection::{ConnectionIo, H2Connection}, error::SendRequestError, }; use crate::BoxError; pub(crate) async fn send_request<Io, B>( mut io: H2Connection<Io>, head: RequestHeadType, body: B, ) -> Result<(ResponseHead, Payload), SendRequestError> where Io: ConnectionIo, B: MessageBody, B::Error: Into<BoxError>, { trace!("Sending client request: {:?} {:?}", head, body.size()); let head_req = head.as_ref().method == Method::HEAD; let length = body.size(); let eof = matches!(length, BodySize::None | BodySize::Sized(0)); let mut req = Request::new(()); *req.uri_mut() = head.as_ref().uri.clone(); *req.method_mut() = head.as_ref().method.clone(); *req.version_mut() = Version::HTTP_2; let mut skip_len = true; // let mut has_date = false; // Content length let _ = match length { BodySize::None => None, BodySize::Sized(0) => { #[allow(clippy::declare_interior_mutable_const)] const HV_ZERO: HeaderValue = HeaderValue::from_static("0"); req.headers_mut().insert(CONTENT_LENGTH, HV_ZERO) } BodySize::Sized(len) => { let mut buf = itoa::Buffer::new(); req.headers_mut().insert( CONTENT_LENGTH, HeaderValue::from_str(buf.format(len)).unwrap(), ) } BodySize::Stream => { skip_len = false; None } }; // Extracting extra headers from RequestHeadType. HeaderMap::new() does not allocate. let (head, extra_headers) = match head { RequestHeadType::Owned(head) => (RequestHeadType::Owned(head), HeaderMap::new()), RequestHeadType::Rc(head, extra_headers) => ( RequestHeadType::Rc(head, None), extra_headers.unwrap_or_else(HeaderMap::new), ), }; // merging headers from head and extra headers. let headers = head .as_ref() .headers .iter() .filter(|(name, _)| !extra_headers.contains_key(*name)) .chain(extra_headers.iter()); // copy headers for (key, value) in headers { match *key { // TODO: consider skipping other headers according to: // https://datatracker.ietf.org/doc/html/rfc7540#section-8.1.2.2 // omit HTTP/1.x only headers CONNECTION | TRANSFER_ENCODING | HOST => continue, CONTENT_LENGTH if skip_len => continue, // DATE => has_date = true, _ => {} } req.headers_mut().append(key, value.clone()); } let res = poll_fn(|cx| io.poll_ready(cx)).await; if let Err(err) = res { io.on_release(err.is_io() || err.is_go_away()); return Err(SendRequestError::from(err)); } let resp = match io.send_request(req, eof) { Ok((fut, send)) => { io.on_release(false); if !eof { send_body(body, send).await?; } fut.await.map_err(SendRequestError::from)? } Err(err) => { io.on_release(err.is_io() || err.is_go_away()); return Err(err.into()); } }; let (parts, body) = resp.into_parts(); let payload = if head_req { Payload::None } else { body.into() }; let mut head = ResponseHead::new(parts.status); head.version = parts.version; head.headers = parts.headers.into(); Ok((head, payload)) } async fn send_body<B>(body: B, mut send: SendStream<Bytes>) -> Result<(), SendRequestError> where B: MessageBody, B::Error: Into<BoxError>, { let mut buf = None; actix_rt::pin!(body); loop { if buf.is_none() { match poll_fn(|cx| body.as_mut().poll_next(cx)).await { Some(Ok(b)) => { send.reserve_capacity(b.len()); buf = Some(b); } Some(Err(err)) => return Err(SendRequestError::Body(err.into())), None => { if let Err(err) = send.send_data(Bytes::new(), true) { return Err(err.into()); } send.reserve_capacity(0); return Ok(()); } } } match poll_fn(|cx| send.poll_capacity(cx)).await { None => return Ok(()), Some(Ok(cap)) => { let b = buf.as_mut().unwrap(); let len = b.len(); let bytes = b.split_to(std::cmp::min(cap, len)); if let Err(err) = send.send_data(bytes, false) { return Err(err.into()); } if !b.is_empty() { send.reserve_capacity(b.len()); } else { buf = None; } continue; } Some(Err(err)) => return Err(err.into()), } } } pub(crate) fn handshake<Io: ConnectionIo>( io: Io, config: &ConnectorConfig, ) -> impl Future<Output = Result<(SendRequest<Bytes>, Connection<Io, Bytes>), h2::Error>> { let mut builder = Builder::new(); builder .initial_window_size(config.stream_window_size) .initial_connection_window_size(config.conn_window_size) .enable_push(false); builder.handshake(io) }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/client/connector.rs
awc/src/client/connector.rs
use std::{ fmt, future::Future, net::IpAddr, pin::Pin, rc::Rc, task::{Context, Poll}, time::Duration, }; use actix_http::Protocol; use actix_rt::{ net::{ActixStream, TcpStream}, time::{sleep, Sleep}, }; use actix_service::Service; use actix_tls::connect::{ ConnectError as TcpConnectError, ConnectInfo, Connection as TcpConnection, Connector as TcpConnector, Resolver, }; use futures_core::{future::LocalBoxFuture, ready}; use http::Uri; use pin_project_lite::pin_project; use super::{ config::ConnectorConfig, connection::{Connection, ConnectionIo}, error::ConnectError, pool::ConnectionPool, Connect, }; enum OurTlsConnector { #[allow(dead_code)] // only dead when no TLS feature is enabled None, #[cfg(feature = "openssl")] Openssl(actix_tls::connect::openssl::reexports::SslConnector), /// Provided because building the OpenSSL context on newer versions can be very slow. /// This prevents unnecessary calls to `.build()` while constructing the client connector. #[cfg(feature = "openssl")] #[allow(dead_code)] // false positive; used in build_tls OpensslBuilder(actix_tls::connect::openssl::reexports::SslConnectorBuilder), #[cfg(feature = "rustls-0_20")] #[allow(dead_code)] // false positive; used in build_tls Rustls020(std::sync::Arc<actix_tls::connect::rustls_0_20::reexports::ClientConfig>), #[cfg(feature = "rustls-0_21")] #[allow(dead_code)] // false positive; used in build_tls Rustls021(std::sync::Arc<actix_tls::connect::rustls_0_21::reexports::ClientConfig>), #[cfg(any( feature = "rustls-0_22-webpki-roots", feature = "rustls-0_22-native-roots", ))] #[allow(dead_code)] // false positive; used in build_tls Rustls022(std::sync::Arc<actix_tls::connect::rustls_0_22::reexports::ClientConfig>), #[cfg(feature = "rustls-0_23")] #[allow(dead_code)] // false positive; used in build_tls Rustls023(std::sync::Arc<actix_tls::connect::rustls_0_23::reexports::ClientConfig>), } /// Manages HTTP client network connectivity. /// /// The `Connector` type uses a builder-like combinator pattern for service construction that /// finishes by calling the `.finish()` method. /// /// ```no_run /// use std::time::Duration; /// /// let connector = awc::Connector::new() /// .timeout(Duration::from_secs(5)) /// .finish(); /// ``` pub struct Connector<T> { connector: T, config: ConnectorConfig, #[allow(dead_code)] // only dead when no TLS feature is enabled tls: OurTlsConnector, } impl Connector<()> { /// Create a new connector with default TLS settings /// /// # Panics /// /// - When the `rustls-0_23-webpki-roots` or `rustls-0_23-native-roots` features are enabled /// and no default crypto provider has been loaded, this method will panic. /// - When the `rustls-0_23-native-roots` or `rustls-0_22-native-roots` features are enabled /// and the runtime system has no native root certificates, this method will panic. #[allow(clippy::new_ret_no_self, clippy::let_unit_value)] pub fn new() -> Connector< impl Service< ConnectInfo<Uri>, Response = TcpConnection<Uri, TcpStream>, Error = actix_tls::connect::ConnectError, > + Clone, > { Connector { connector: TcpConnector::new(resolver::resolver()).service(), config: ConnectorConfig::default(), tls: Self::build_tls(vec![b"h2".to_vec(), b"http/1.1".to_vec()]), } } cfg_if::cfg_if! { if #[cfg(any(feature = "rustls-0_23-webpki-roots", feature = "rustls-0_23-native-roots"))] { /// Build TLS connector with Rustls v0.23, based on supplied ALPN protocols. /// /// Note that if other TLS crate features are enabled, Rustls v0.23 will be used. fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector { use actix_tls::connect::rustls_0_23::{self, reexports::ClientConfig}; cfg_if::cfg_if! { if #[cfg(feature = "rustls-0_23-webpki-roots")] { let certs = rustls_0_23::webpki_roots_cert_store(); } else if #[cfg(feature = "rustls-0_23-native-roots")] { let certs = rustls_0_23::native_roots_cert_store().expect("Failed to find native root certificates"); } } let mut config = ClientConfig::builder() .with_root_certificates(certs) .with_no_client_auth(); config.alpn_protocols = protocols; OurTlsConnector::Rustls023(std::sync::Arc::new(config)) } } else if #[cfg(any(feature = "rustls-0_22-webpki-roots", feature = "rustls-0_22-native-roots"))] { /// Build TLS connector with Rustls v0.22, based on supplied ALPN protocols. fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector { use actix_tls::connect::rustls_0_22::{self, reexports::ClientConfig}; cfg_if::cfg_if! { if #[cfg(feature = "rustls-0_22-webpki-roots")] { let certs = rustls_0_22::webpki_roots_cert_store(); } else if #[cfg(feature = "rustls-0_22-native-roots")] { let certs = rustls_0_22::native_roots_cert_store().expect("Failed to find native root certificates"); } } let mut config = ClientConfig::builder() .with_root_certificates(certs) .with_no_client_auth(); config.alpn_protocols = protocols; OurTlsConnector::Rustls022(std::sync::Arc::new(config)) } } else if #[cfg(feature = "rustls-0_21")] { /// Build TLS connector with Rustls v0.21, based on supplied ALPN protocols. fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector { use actix_tls::connect::rustls_0_21::{reexports::ClientConfig, webpki_roots_cert_store}; let mut config = ClientConfig::builder() .with_safe_defaults() .with_root_certificates(webpki_roots_cert_store()) .with_no_client_auth(); config.alpn_protocols = protocols; OurTlsConnector::Rustls021(std::sync::Arc::new(config)) } } else if #[cfg(feature = "rustls-0_20")] { /// Build TLS connector with Rustls v0.20, based on supplied ALPN protocols. fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector { use actix_tls::connect::rustls_0_20::{reexports::ClientConfig, webpki_roots_cert_store}; let mut config = ClientConfig::builder() .with_safe_defaults() .with_root_certificates(webpki_roots_cert_store()) .with_no_client_auth(); config.alpn_protocols = protocols; OurTlsConnector::Rustls020(std::sync::Arc::new(config)) } } else if #[cfg(feature = "openssl")] { /// Build TLS connector with OpenSSL, based on supplied ALPN protocols. fn build_tls(protocols: Vec<Vec<u8>>) -> OurTlsConnector { use actix_tls::connect::openssl::reexports::{SslConnector, SslMethod}; use bytes::{BufMut, BytesMut}; let mut alpn = BytesMut::with_capacity(20); for proto in &protocols { alpn.put_u8(proto.len() as u8); alpn.put(proto.as_slice()); } let mut ssl = SslConnector::builder(SslMethod::tls()).unwrap(); if let Err(err) = ssl.set_alpn_protos(&alpn) { log::error!("Can not set ALPN protocol: {err:?}"); } OurTlsConnector::OpensslBuilder(ssl) } } else { /// Provides an empty TLS connector when no TLS feature is enabled, or when only the /// `rustls-0_23` crate feature is enabled. fn build_tls(_: Vec<Vec<u8>>) -> OurTlsConnector { OurTlsConnector::None } } } } impl<S> Connector<S> { /// Sets custom connector. pub fn connector<S1, Io1>(self, connector: S1) -> Connector<S1> where Io1: ActixStream + fmt::Debug + 'static, S1: Service<ConnectInfo<Uri>, Response = TcpConnection<Uri, Io1>, Error = TcpConnectError> + Clone, { Connector { connector, config: self.config, tls: self.tls, } } } impl<S, IO> Connector<S> where // Note: // Input Io type is bound to ActixStream trait but internally in client module they // are bound to ConnectionIo trait alias. And latter is the trait exposed to public // in the form of Box<dyn ConnectionIo> type. // // This remap is to hide ActixStream's trait methods. They are not meant to be called // from user code. IO: ActixStream + fmt::Debug + 'static, S: Service<ConnectInfo<Uri>, Response = TcpConnection<Uri, IO>, Error = TcpConnectError> + Clone + 'static, { /// Sets TCP connection timeout. /// /// This is the max time allowed to connect to remote host, including DNS name resolution. /// /// By default, the timeout is 5 seconds. pub fn timeout(mut self, timeout: Duration) -> Self { self.config.timeout = timeout; self } /// Sets TLS handshake timeout. /// /// This is the max time allowed to perform the TLS handshake with remote host after TCP /// connection is established. /// /// By default, the timeout is 5 seconds. pub fn handshake_timeout(mut self, timeout: Duration) -> Self { self.config.handshake_timeout = timeout; self } /// Sets custom OpenSSL `SslConnector` instance. #[cfg(feature = "openssl")] pub fn openssl( mut self, connector: actix_tls::connect::openssl::reexports::SslConnector, ) -> Self { self.tls = OurTlsConnector::Openssl(connector); self } /// See docs for [`Connector::openssl`]. #[doc(hidden)] #[cfg(feature = "openssl")] #[deprecated(since = "3.0.0", note = "Renamed to `Connector::openssl`.")] pub fn ssl(mut self, connector: actix_tls::connect::openssl::reexports::SslConnector) -> Self { self.tls = OurTlsConnector::Openssl(connector); self } /// Sets custom Rustls v0.20 `ClientConfig` instance. #[cfg(feature = "rustls-0_20")] pub fn rustls( mut self, connector: std::sync::Arc<actix_tls::connect::rustls_0_20::reexports::ClientConfig>, ) -> Self { self.tls = OurTlsConnector::Rustls020(connector); self } /// Sets custom Rustls v0.21 `ClientConfig` instance. #[cfg(feature = "rustls-0_21")] pub fn rustls_021( mut self, connector: std::sync::Arc<actix_tls::connect::rustls_0_21::reexports::ClientConfig>, ) -> Self { self.tls = OurTlsConnector::Rustls021(connector); self } /// Sets custom Rustls v0.22 `ClientConfig` instance. #[cfg(any( feature = "rustls-0_22-webpki-roots", feature = "rustls-0_22-native-roots", ))] pub fn rustls_0_22( mut self, connector: std::sync::Arc<actix_tls::connect::rustls_0_22::reexports::ClientConfig>, ) -> Self { self.tls = OurTlsConnector::Rustls022(connector); self } /// Sets custom Rustls v0.23 `ClientConfig` instance. /// /// In order to enable ALPN, set the `.alpn_protocols` field on the ClientConfig to the /// following: /// /// ```no_run /// vec![b"h2".to_vec(), b"http/1.1".to_vec()] /// # ; /// ``` #[cfg(feature = "rustls-0_23")] pub fn rustls_0_23( mut self, connector: std::sync::Arc<actix_tls::connect::rustls_0_23::reexports::ClientConfig>, ) -> Self { self.tls = OurTlsConnector::Rustls023(connector); self } /// Sets maximum supported HTTP major version. /// /// Supported versions are HTTP/1.1 and HTTP/2. pub fn max_http_version(mut self, val: http::Version) -> Self { let versions = match val { http::Version::HTTP_11 => vec![b"http/1.1".to_vec()], http::Version::HTTP_2 => vec![b"h2".to_vec(), b"http/1.1".to_vec()], _ => { unimplemented!("actix-http client only supports versions http/1.1 & http/2") } }; self.tls = Connector::build_tls(versions); self } /// Sets the initial window size (in bytes) for HTTP/2 stream-level flow control for received /// data. /// /// The default value is 65,535 and is good for APIs, but not for big objects. pub fn initial_window_size(mut self, size: u32) -> Self { self.config.stream_window_size = size; self } /// Sets the initial window size (in bytes) for HTTP/2 connection-level flow control for /// received data. /// /// The default value is 65,535 and is good for APIs, but not for big objects. pub fn initial_connection_window_size(mut self, size: u32) -> Self { self.config.conn_window_size = size; self } /// Set total number of simultaneous connections per type of scheme. /// /// If limit is 0, the connector has no limit. /// /// The default limit size is 100. pub fn limit(mut self, limit: usize) -> Self { if limit == 0 { self.config.limit = u32::MAX as usize; } else { self.config.limit = limit; } self } /// Set keep-alive period for opened connection. /// /// Keep-alive period is the period between connection usage. If /// the delay between repeated usages of the same connection /// exceeds this period, the connection is closed. /// Default keep-alive period is 15 seconds. pub fn conn_keep_alive(mut self, dur: Duration) -> Self { self.config.conn_keep_alive = dur; self } /// Set max lifetime period for connection. /// /// Connection lifetime is max lifetime of any opened connection /// until it is closed regardless of keep-alive period. /// Default lifetime period is 75 seconds. pub fn conn_lifetime(mut self, dur: Duration) -> Self { self.config.conn_lifetime = dur; self } /// Set server connection disconnect timeout in milliseconds. /// /// Defines a timeout for disconnect connection. If a disconnect procedure does not complete /// within this time, the socket get dropped. This timeout affects only secure connections. /// /// To disable timeout set value to 0. /// /// By default disconnect timeout is set to 3000 milliseconds. pub fn disconnect_timeout(mut self, dur: Duration) -> Self { self.config.disconnect_timeout = Some(dur); self } /// Set local IP Address the connector would use for establishing connection. pub fn local_address(mut self, addr: IpAddr) -> Self { self.config.local_address = Some(addr); self } /// Finish configuration process and create connector service. /// /// The `Connector` builder always concludes by calling `finish()` last in its combinator chain. pub fn finish(self) -> ConnectorService<S, IO> { let local_address = self.config.local_address; let timeout = self.config.timeout; let tcp_service_inner = TcpConnectorInnerService::new(self.connector, timeout, local_address); #[allow(clippy::redundant_clone)] let tcp_service = TcpConnectorService { service: tcp_service_inner.clone(), }; let tls = match self.tls { #[cfg(feature = "openssl")] OurTlsConnector::OpensslBuilder(builder) => OurTlsConnector::Openssl(builder.build()), tls => tls, }; let tls_service = match tls { OurTlsConnector::None => { #[cfg(not(feature = "dangerous-h2c"))] { None } #[cfg(feature = "dangerous-h2c")] { use std::io; use actix_tls::connect::Connection; use actix_utils::future::{ready, Ready}; #[allow(non_local_definitions)] impl IntoConnectionIo for TcpConnection<Uri, Box<dyn ConnectionIo>> { fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) { let io = self.into_parts().0; (io, Protocol::Http2) } } /// With the `dangerous-h2c` feature enabled, this connector uses a no-op TLS /// connection service that passes through plain TCP as a TLS connection. /// /// The protocol version of this fake TLS connection is set to be HTTP/2. #[derive(Clone)] struct NoOpTlsConnectorService; impl<R, IO> Service<Connection<R, IO>> for NoOpTlsConnectorService where IO: ActixStream + 'static, { type Response = Connection<R, Box<dyn ConnectionIo>>; type Error = io::Error; type Future = Ready<Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, connection: Connection<R, IO>) -> Self::Future { let (io, connection) = connection.replace_io(()); let (_, connection) = connection.replace_io(Box::new(io) as _); ready(Ok(connection)) } } let handshake_timeout = self.config.handshake_timeout; let tls_service = TlsConnectorService { tcp_service: tcp_service_inner, tls_service: NoOpTlsConnectorService, timeout: handshake_timeout, }; Some(actix_service::boxed::rc_service(tls_service)) } } #[cfg(feature = "openssl")] OurTlsConnector::Openssl(tls) => { const H2: &[u8] = b"h2"; use actix_tls::connect::openssl::{reexports::AsyncSslStream, TlsConnector}; #[allow(non_local_definitions)] impl<IO: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncSslStream<IO>> { fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) { let sock = self.into_parts().0; let h2 = sock .ssl() .selected_alpn_protocol() .is_some_and(|protos| protos.windows(2).any(|w| w == H2)); if h2 { (Box::new(sock), Protocol::Http2) } else { (Box::new(sock), Protocol::Http1) } } } let handshake_timeout = self.config.handshake_timeout; let tls_service = TlsConnectorService { tcp_service: tcp_service_inner, tls_service: TlsConnector::service(tls), timeout: handshake_timeout, }; Some(actix_service::boxed::rc_service(tls_service)) } #[cfg(feature = "openssl")] OurTlsConnector::OpensslBuilder(_) => { unreachable!("OpenSSL builder is built before this match."); } #[cfg(feature = "rustls-0_20")] OurTlsConnector::Rustls020(tls) => { const H2: &[u8] = b"h2"; use actix_tls::connect::rustls_0_20::{reexports::AsyncTlsStream, TlsConnector}; #[allow(non_local_definitions)] impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncTlsStream<Io>> { fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) { let sock = self.into_parts().0; let h2 = sock .get_ref() .1 .alpn_protocol() .is_some_and(|protos| protos.windows(2).any(|w| w == H2)); if h2 { (Box::new(sock), Protocol::Http2) } else { (Box::new(sock), Protocol::Http1) } } } let handshake_timeout = self.config.handshake_timeout; let tls_service = TlsConnectorService { tcp_service: tcp_service_inner, tls_service: TlsConnector::service(tls), timeout: handshake_timeout, }; Some(actix_service::boxed::rc_service(tls_service)) } #[cfg(feature = "rustls-0_21")] OurTlsConnector::Rustls021(tls) => { const H2: &[u8] = b"h2"; use actix_tls::connect::rustls_0_21::{reexports::AsyncTlsStream, TlsConnector}; #[allow(non_local_definitions)] impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncTlsStream<Io>> { fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) { let sock = self.into_parts().0; let h2 = sock .get_ref() .1 .alpn_protocol() .is_some_and(|protos| protos.windows(2).any(|w| w == H2)); if h2 { (Box::new(sock), Protocol::Http2) } else { (Box::new(sock), Protocol::Http1) } } } let handshake_timeout = self.config.handshake_timeout; let tls_service = TlsConnectorService { tcp_service: tcp_service_inner, tls_service: TlsConnector::service(tls), timeout: handshake_timeout, }; Some(actix_service::boxed::rc_service(tls_service)) } #[cfg(any( feature = "rustls-0_22-webpki-roots", feature = "rustls-0_22-native-roots", ))] OurTlsConnector::Rustls022(tls) => { const H2: &[u8] = b"h2"; use actix_tls::connect::rustls_0_22::{reexports::AsyncTlsStream, TlsConnector}; #[allow(non_local_definitions)] impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncTlsStream<Io>> { fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) { let sock = self.into_parts().0; let h2 = sock .get_ref() .1 .alpn_protocol() .is_some_and(|protos| protos.windows(2).any(|w| w == H2)); if h2 { (Box::new(sock), Protocol::Http2) } else { (Box::new(sock), Protocol::Http1) } } } let handshake_timeout = self.config.handshake_timeout; let tls_service = TlsConnectorService { tcp_service: tcp_service_inner, tls_service: TlsConnector::service(tls), timeout: handshake_timeout, }; Some(actix_service::boxed::rc_service(tls_service)) } #[cfg(feature = "rustls-0_23")] OurTlsConnector::Rustls023(tls) => { const H2: &[u8] = b"h2"; use actix_tls::connect::rustls_0_23::{reexports::AsyncTlsStream, TlsConnector}; #[allow(non_local_definitions)] impl<Io: ConnectionIo> IntoConnectionIo for TcpConnection<Uri, AsyncTlsStream<Io>> { fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol) { let sock = self.into_parts().0; let h2 = sock .get_ref() .1 .alpn_protocol() .is_some_and(|protos| protos.windows(2).any(|w| w == H2)); if h2 { (Box::new(sock), Protocol::Http2) } else { (Box::new(sock), Protocol::Http1) } } } let handshake_timeout = self.config.handshake_timeout; let tls_service = TlsConnectorService { tcp_service: tcp_service_inner, tls_service: TlsConnector::service(tls), timeout: handshake_timeout, }; Some(actix_service::boxed::rc_service(tls_service)) } }; let tcp_config = self.config.no_disconnect_timeout(); let tcp_pool = ConnectionPool::new(tcp_service, tcp_config); let tls_config = self.config; let tls_pool = tls_service.map(move |tls_service| ConnectionPool::new(tls_service, tls_config)); ConnectorServicePriv { tcp_pool, tls_pool } } } /// tcp service for map `TcpConnection<Uri, Io>` type to `(Io, Protocol)` #[derive(Clone)] pub struct TcpConnectorService<S: Clone> { service: S, } impl<S, Io> Service<Connect> for TcpConnectorService<S> where S: Service<Connect, Response = TcpConnection<Uri, Io>, Error = ConnectError> + Clone + 'static, { type Response = (Io, Protocol); type Error = ConnectError; type Future = TcpConnectorFuture<S::Future>; actix_service::forward_ready!(service); fn call(&self, req: Connect) -> Self::Future { TcpConnectorFuture { fut: self.service.call(req), } } } pin_project! { #[project = TcpConnectorFutureProj] pub struct TcpConnectorFuture<Fut> { #[pin] fut: Fut, } } impl<Fut, Io> Future for TcpConnectorFuture<Fut> where Fut: Future<Output = Result<TcpConnection<Uri, Io>, ConnectError>>, { type Output = Result<(Io, Protocol), ConnectError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.project() .fut .poll(cx) .map_ok(|res| (res.into_parts().0, Protocol::Http1)) } } /// service for establish tcp connection and do client tls handshake. /// operation is canceled when timeout limit reached. #[cfg(any( feature = "dangerous-h2c", feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21", feature = "rustls-0_22-webpki-roots", feature = "rustls-0_22-native-roots", feature = "rustls-0_23", feature = "rustls-0_23-webpki-roots", feature = "rustls-0_23-native-roots" ))] struct TlsConnectorService<Tcp, Tls> { /// TCP connection is canceled on `TcpConnectorInnerService`'s timeout setting. tcp_service: Tcp, /// TLS connection is canceled on `TlsConnectorService`'s timeout setting. tls_service: Tls, timeout: Duration, } #[cfg(any( feature = "dangerous-h2c", feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21", feature = "rustls-0_22-webpki-roots", feature = "rustls-0_22-native-roots", feature = "rustls-0_23", ))] impl<Tcp, Tls, IO> Service<Connect> for TlsConnectorService<Tcp, Tls> where Tcp: Service<Connect, Response = TcpConnection<Uri, IO>, Error = ConnectError> + Clone + 'static, Tls: Service<TcpConnection<Uri, IO>, Error = std::io::Error> + Clone + 'static, Tls::Response: IntoConnectionIo, IO: ConnectionIo, { type Response = (Box<dyn ConnectionIo>, Protocol); type Error = ConnectError; type Future = TlsConnectorFuture<Tls, Tcp::Future, Tls::Future>; fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { ready!(self.tcp_service.poll_ready(cx))?; ready!(self.tls_service.poll_ready(cx))?; Poll::Ready(Ok(())) } fn call(&self, req: Connect) -> Self::Future { let fut = self.tcp_service.call(req); let tls_service = self.tls_service.clone(); let timeout = self.timeout; TlsConnectorFuture::TcpConnect { fut, tls_service: Some(tls_service), timeout, } } } pin_project! { #[project = TlsConnectorProj] #[allow(clippy::large_enum_variant)] enum TlsConnectorFuture<S, Fut1, Fut2> { TcpConnect { #[pin] fut: Fut1, tls_service: Option<S>, timeout: Duration, }, TlsConnect { #[pin] fut: Fut2, #[pin] timeout: Sleep, }, } } /// helper trait for generic over different TlsStream types between tls crates. trait IntoConnectionIo { fn into_connection_io(self) -> (Box<dyn ConnectionIo>, Protocol); } impl<S, Io, Fut1, Fut2, Res> Future for TlsConnectorFuture<S, Fut1, Fut2> where S: Service<TcpConnection<Uri, Io>, Response = Res, Error = std::io::Error, Future = Fut2>, S::Response: IntoConnectionIo, Fut1: Future<Output = Result<TcpConnection<Uri, Io>, ConnectError>>, Fut2: Future<Output = Result<S::Response, S::Error>>, Io: ConnectionIo, { type Output = Result<(Box<dyn ConnectionIo>, Protocol), ConnectError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match self.as_mut().project() { TlsConnectorProj::TcpConnect { fut, tls_service, timeout, } => { let res = ready!(fut.poll(cx))?; let fut = tls_service .take() .expect("TlsConnectorFuture polled after complete") .call(res); let timeout = sleep(*timeout); self.set(TlsConnectorFuture::TlsConnect { fut, timeout }); self.poll(cx) } TlsConnectorProj::TlsConnect { fut, timeout } => match fut.poll(cx)? { Poll::Ready(res) => Poll::Ready(Ok(res.into_connection_io())), Poll::Pending => timeout.poll(cx).map(|_| Err(ConnectError::Timeout)), }, } } } /// service for establish tcp connection. /// operation is canceled when timeout limit reached. #[derive(Clone)] pub struct TcpConnectorInnerService<S: Clone> { service: S, timeout: Duration, local_address: Option<std::net::IpAddr>, } impl<S: Clone> TcpConnectorInnerService<S> { fn new(service: S, timeout: Duration, local_address: Option<std::net::IpAddr>) -> Self { Self { service, timeout, local_address, } } } impl<S, Io> Service<Connect> for TcpConnectorInnerService<S> where S: Service<ConnectInfo<Uri>, Response = TcpConnection<Uri, Io>, Error = TcpConnectError> + Clone + 'static, { type Response = S::Response; type Error = ConnectError; type Future = TcpConnectorInnerFuture<S::Future>; actix_service::forward_ready!(service); fn call(&self, req: Connect) -> Self::Future { let mut req = ConnectInfo::new(req.uri).set_addr(req.addr); if let Some(local_addr) = self.local_address { req = req.set_local_addr(local_addr); } TcpConnectorInnerFuture { fut: self.service.call(req), timeout: sleep(self.timeout), } } } pin_project! { #[project = TcpConnectorInnerFutureProj]
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
true
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/client/connection.rs
awc/src/client/connection.rs
use std::{ io, ops::{Deref, DerefMut}, pin::Pin, task::{Context, Poll}, time, }; use actix_codec::{AsyncRead, AsyncWrite, Framed, ReadBuf}; use actix_http::{body::MessageBody, h1::ClientCodec, Payload, RequestHeadType, ResponseHead}; use actix_rt::task::JoinHandle; use bytes::Bytes; use futures_core::future::LocalBoxFuture; use h2::client::SendRequest; use super::{error::SendRequestError, h1proto, h2proto, pool::Acquired}; use crate::BoxError; /// Trait alias for types impl [tokio::io::AsyncRead] and [tokio::io::AsyncWrite]. pub trait ConnectionIo: AsyncRead + AsyncWrite + Unpin + 'static {} impl<T: AsyncRead + AsyncWrite + Unpin + 'static> ConnectionIo for T {} /// HTTP client connection pub struct H1Connection<Io: ConnectionIo> { io: Option<Io>, created: time::Instant, acquired: Acquired<Io>, } impl<Io: ConnectionIo> H1Connection<Io> { /// close or release the connection to pool based on flag input pub(super) fn on_release(&mut self, keep_alive: bool) { if keep_alive { self.release(); } else { self.close(); } } /// Close connection fn close(&mut self) { let io = self.io.take().unwrap(); self.acquired.close(ConnectionInnerType::H1(io)); } /// Release this connection to the connection pool fn release(&mut self) { let io = self.io.take().unwrap(); self.acquired .release(ConnectionInnerType::H1(io), self.created); } fn io_pin_mut(self: Pin<&mut Self>) -> Pin<&mut Io> { Pin::new(self.get_mut().io.as_mut().unwrap()) } } impl<Io: ConnectionIo> AsyncRead for H1Connection<Io> { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { self.io_pin_mut().poll_read(cx, buf) } } impl<Io: ConnectionIo> AsyncWrite for H1Connection<Io> { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { self.io_pin_mut().poll_write(cx, buf) } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { self.io_pin_mut().poll_flush(cx) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> { self.io_pin_mut().poll_shutdown(cx) } fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>], ) -> Poll<io::Result<usize>> { self.io_pin_mut().poll_write_vectored(cx, bufs) } fn is_write_vectored(&self) -> bool { self.io.as_ref().unwrap().is_write_vectored() } } /// HTTP2 client connection pub struct H2Connection<Io: ConnectionIo> { io: Option<H2ConnectionInner>, created: time::Instant, acquired: Acquired<Io>, } impl<Io: ConnectionIo> Deref for H2Connection<Io> { type Target = SendRequest<Bytes>; fn deref(&self) -> &Self::Target { &self.io.as_ref().unwrap().sender } } impl<Io: ConnectionIo> DerefMut for H2Connection<Io> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.io.as_mut().unwrap().sender } } impl<Io: ConnectionIo> H2Connection<Io> { /// close or release the connection to pool based on flag input pub(super) fn on_release(&mut self, close: bool) { if close { self.close(); } else { self.release(); } } /// Close connection fn close(&mut self) { let io = self.io.take().unwrap(); self.acquired.close(ConnectionInnerType::H2(io)); } /// Release this connection to the connection pool fn release(&mut self) { let io = self.io.take().unwrap(); self.acquired .release(ConnectionInnerType::H2(io), self.created); } } /// `H2ConnectionInner` has two parts: `SendRequest` and `Connection`. /// /// `Connection` is spawned as an async task on runtime and `H2ConnectionInner` holds a handle /// for this task. Therefore, it can wake up and quit the task when SendRequest is dropped. pub(super) struct H2ConnectionInner { handle: JoinHandle<()>, sender: SendRequest<Bytes>, } impl H2ConnectionInner { pub(super) fn new<Io: ConnectionIo>( sender: SendRequest<Bytes>, connection: h2::client::Connection<Io>, ) -> Self { let handle = actix_rt::spawn(async move { let _ = connection.await; }); Self { handle, sender } } } /// Cancel spawned connection task on drop. impl Drop for H2ConnectionInner { fn drop(&mut self) { // TODO: this can end up sending extraneous requests; see if there is a better way to handle if self .sender .send_request(http::Request::new(()), true) .is_err() { self.handle.abort(); } } } /// Unified connection type cover HTTP/1 Plain/TLS and HTTP/2 protocols. #[allow(dead_code)] pub enum Connection<A, B = Box<dyn ConnectionIo>> where A: ConnectionIo, B: ConnectionIo, { Tcp(ConnectionType<A>), Tls(ConnectionType<B>), } /// Unified connection type cover Http1/2 protocols pub enum ConnectionType<Io: ConnectionIo> { H1(H1Connection<Io>), H2(H2Connection<Io>), } /// Helper type for storing connection types in pool. pub(super) enum ConnectionInnerType<Io> { H1(Io), H2(H2ConnectionInner), } impl<Io: ConnectionIo> ConnectionType<Io> { pub(super) fn from_pool( inner: ConnectionInnerType<Io>, created: time::Instant, acquired: Acquired<Io>, ) -> Self { match inner { ConnectionInnerType::H1(io) => Self::from_h1(io, created, acquired), ConnectionInnerType::H2(io) => Self::from_h2(io, created, acquired), } } pub(super) fn from_h1(io: Io, created: time::Instant, acquired: Acquired<Io>) -> Self { Self::H1(H1Connection { io: Some(io), created, acquired, }) } pub(super) fn from_h2( io: H2ConnectionInner, created: time::Instant, acquired: Acquired<Io>, ) -> Self { Self::H2(H2Connection { io: Some(io), created, acquired, }) } } impl<A, B> Connection<A, B> where A: ConnectionIo, B: ConnectionIo, { /// Send a request through connection. pub fn send_request<RB, H>( self, head: H, body: RB, ) -> LocalBoxFuture<'static, Result<(ResponseHead, Payload), SendRequestError>> where H: Into<RequestHeadType> + 'static, RB: MessageBody + 'static, RB::Error: Into<BoxError>, { Box::pin(async move { match self { Connection::Tcp(ConnectionType::H1(conn)) => { h1proto::send_request(conn, head.into(), body).await } Connection::Tls(ConnectionType::H1(conn)) => { h1proto::send_request(conn, head.into(), body).await } Connection::Tls(ConnectionType::H2(conn)) => { h2proto::send_request(conn, head.into(), body).await } _ => { unreachable!("Plain TCP connection can be used only with HTTP/1.1 protocol") } } }) } /// Send request, returns Response and Framed tunnel. pub fn open_tunnel<H: Into<RequestHeadType> + 'static>( self, head: H, ) -> LocalBoxFuture< 'static, Result<(ResponseHead, Framed<Connection<A, B>, ClientCodec>), SendRequestError>, > { Box::pin(async move { match self { Connection::Tcp(ConnectionType::H1(ref _conn)) => { let (head, framed) = h1proto::open_tunnel(self, head.into()).await?; Ok((head, framed)) } Connection::Tls(ConnectionType::H1(ref _conn)) => { let (head, framed) = h1proto::open_tunnel(self, head.into()).await?; Ok((head, framed)) } Connection::Tls(ConnectionType::H2(mut conn)) => { conn.release(); Err(SendRequestError::TunnelNotSupported) } Connection::Tcp(ConnectionType::H2(_)) => { unreachable!("Plain Tcp connection can be used only in Http1 protocol") } } }) } } impl<A, B> AsyncRead for Connection<A, B> where A: ConnectionIo, B: ConnectionIo, { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { match self.get_mut() { Connection::Tcp(ConnectionType::H1(conn)) => Pin::new(conn).poll_read(cx, buf), Connection::Tls(ConnectionType::H1(conn)) => Pin::new(conn).poll_read(cx, buf), _ => unreachable!("H2Connection can not impl AsyncRead trait"), } } } const H2_UNREACHABLE_WRITE: &str = "H2Connection can not impl AsyncWrite trait"; impl<A, B> AsyncWrite for Connection<A, B> where A: ConnectionIo, B: ConnectionIo, { fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { match self.get_mut() { Connection::Tcp(ConnectionType::H1(conn)) => Pin::new(conn).poll_write(cx, buf), Connection::Tls(ConnectionType::H1(conn)) => Pin::new(conn).poll_write(cx, buf), _ => unreachable!("{}", H2_UNREACHABLE_WRITE), } } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { match self.get_mut() { Connection::Tcp(ConnectionType::H1(conn)) => Pin::new(conn).poll_flush(cx), Connection::Tls(ConnectionType::H1(conn)) => Pin::new(conn).poll_flush(cx), _ => unreachable!("{}", H2_UNREACHABLE_WRITE), } } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { match self.get_mut() { Connection::Tcp(ConnectionType::H1(conn)) => Pin::new(conn).poll_shutdown(cx), Connection::Tls(ConnectionType::H1(conn)) => Pin::new(conn).poll_shutdown(cx), _ => unreachable!("{}", H2_UNREACHABLE_WRITE), } } fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[io::IoSlice<'_>], ) -> Poll<io::Result<usize>> { match self.get_mut() { Connection::Tcp(ConnectionType::H1(conn)) => { Pin::new(conn).poll_write_vectored(cx, bufs) } Connection::Tls(ConnectionType::H1(conn)) => { Pin::new(conn).poll_write_vectored(cx, bufs) } _ => unreachable!("{}", H2_UNREACHABLE_WRITE), } } fn is_write_vectored(&self) -> bool { match *self { Connection::Tcp(ConnectionType::H1(ref conn)) => conn.is_write_vectored(), Connection::Tls(ConnectionType::H1(ref conn)) => conn.is_write_vectored(), _ => unreachable!("{}", H2_UNREACHABLE_WRITE), } } } #[cfg(test)] mod test { use std::{ future::Future, net, time::{Duration, Instant}, }; use actix_rt::{ net::TcpStream, time::{interval, Interval}, }; use super::*; #[actix_rt::test] async fn test_h2_connection_drop() { env_logger::try_init().ok(); let addr = "127.0.0.1:0".parse::<net::SocketAddr>().unwrap(); let listener = net::TcpListener::bind(addr).unwrap(); let local = listener.local_addr().unwrap(); std::thread::spawn(move || while listener.accept().is_ok() {}); let tcp = TcpStream::connect(local).await.unwrap(); let (sender, connection) = h2::client::handshake(tcp).await.unwrap(); let conn = H2ConnectionInner::new(sender.clone(), connection); assert!(sender.clone().ready().await.is_ok()); assert!(h2::client::SendRequest::clone(&conn.sender) .ready() .await .is_ok()); drop(conn); struct DropCheck { sender: h2::client::SendRequest<Bytes>, interval: Interval, start_from: Instant, } impl Future for DropCheck { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); match futures_core::ready!(this.sender.poll_ready(cx)) { Ok(()) => { if this.start_from.elapsed() > Duration::from_secs(10) { panic!("connection should be gone and can not be ready"); } else { match this.interval.poll_tick(cx) { Poll::Ready(_) => { // prevents spurious test hang this.interval.reset(); Poll::Pending } Poll::Pending => Poll::Pending, } } } Err(_) => Poll::Ready(()), } } } DropCheck { sender, interval: interval(Duration::from_millis(100)), start_from: Instant::now(), } .await; } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/client/error.rs
awc/src/client/error.rs
use std::{fmt, io}; use actix_http::error::{HttpError, ParseError}; #[cfg(feature = "openssl")] use actix_tls::accept::openssl::reexports::Error as OpensslError; use derive_more::{Display, From}; use crate::BoxError; /// A set of errors that can occur while connecting to an HTTP host #[derive(Debug, Display, From)] #[non_exhaustive] pub enum ConnectError { /// SSL feature is not enabled #[display("SSL is not supported")] SslIsNotSupported, /// SSL error #[cfg(feature = "openssl")] #[display("{}", _0)] SslError(OpensslError), /// Failed to resolve the hostname #[display("Failed resolving hostname: {}", _0)] Resolver(Box<dyn std::error::Error>), /// No dns records #[display("No DNS records found for the input")] NoRecords, /// Http2 error #[display("{}", _0)] H2(h2::Error), /// Connecting took too long #[display("Timeout while establishing connection")] Timeout, /// Connector has been disconnected #[display("Internal error: connector has been disconnected")] Disconnected, /// Unresolved host name #[display("Connector received `Connect` method with unresolved host")] Unresolved, /// Connection io error #[display("{}", _0)] Io(io::Error), } impl std::error::Error for ConnectError {} impl From<actix_tls::connect::ConnectError> for ConnectError { fn from(err: actix_tls::connect::ConnectError) -> ConnectError { match err { actix_tls::connect::ConnectError::Resolver(err) => ConnectError::Resolver(err), actix_tls::connect::ConnectError::NoRecords => ConnectError::NoRecords, actix_tls::connect::ConnectError::InvalidInput => panic!(), actix_tls::connect::ConnectError::Unresolved => ConnectError::Unresolved, actix_tls::connect::ConnectError::Io(err) => ConnectError::Io(err), } } } #[derive(Debug, Display, From)] #[non_exhaustive] pub enum InvalidUrl { #[display("Missing URL scheme")] MissingScheme, #[display("Unknown URL scheme")] UnknownScheme, #[display("Missing host name")] MissingHost, #[display("URL parse error: {}", _0)] HttpError(http::Error), } impl std::error::Error for InvalidUrl {} /// A set of errors that can occur during request sending and response reading #[derive(Debug, Display, From)] #[non_exhaustive] pub enum SendRequestError { /// Invalid URL #[display("Invalid URL: {}", _0)] Url(InvalidUrl), /// Failed to connect to host #[display("Failed to connect to host: {}", _0)] Connect(ConnectError), /// Error sending request Send(io::Error), /// Error parsing response Response(ParseError), /// Http error #[display("{}", _0)] Http(HttpError), /// Http2 error #[display("{}", _0)] H2(h2::Error), /// Response took too long #[display("Timeout while waiting for response")] Timeout, /// Tunnels are not supported for HTTP/2 connection #[display("Tunnels are not supported for http2 connection")] TunnelNotSupported, /// Error sending request body Body(BoxError), /// Other errors that can occur after submitting a request. #[display("{:?}: {}", _1, _0)] Custom(BoxError, Box<dyn fmt::Debug>), } impl std::error::Error for SendRequestError {} /// A set of errors that can occur during freezing a request #[derive(Debug, Display, From)] #[non_exhaustive] pub enum FreezeRequestError { /// Invalid URL #[display("Invalid URL: {}", _0)] Url(InvalidUrl), /// HTTP error #[display("{}", _0)] Http(HttpError), /// Other errors that can occur after submitting a request. #[display("{:?}: {}", _1, _0)] Custom(BoxError, Box<dyn fmt::Debug>), } impl std::error::Error for FreezeRequestError {} impl From<FreezeRequestError> for SendRequestError { fn from(err: FreezeRequestError) -> Self { match err { FreezeRequestError::Url(err) => err.into(), FreezeRequestError::Http(err) => err.into(), FreezeRequestError::Custom(err, msg) => SendRequestError::Custom(err, msg), } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/client/mod.rs
awc/src/client/mod.rs
//! HTTP client. use std::{rc::Rc, time::Duration}; use actix_http::{error::HttpError, header::HeaderMap, Method, RequestHead, Uri}; use actix_rt::net::TcpStream; use actix_service::Service; pub use actix_tls::connect::{ ConnectError as TcpConnectError, ConnectInfo, Connection as TcpConnection, }; use crate::{ws, BoxConnectorService, ClientBuilder, ClientRequest}; mod config; mod connection; mod connector; mod error; mod h1proto; mod h2proto; mod pool; pub use self::{ connection::{Connection, ConnectionIo}, connector::{Connector, ConnectorService}, error::{ConnectError, FreezeRequestError, InvalidUrl, SendRequestError}, }; #[derive(Clone)] pub struct Connect { pub uri: Uri, pub addr: Option<std::net::SocketAddr>, } /// An asynchronous HTTP and WebSocket client. /// /// You should take care to create, at most, one `Client` per thread. Otherwise, expect higher CPU /// and memory usage. /// /// # Examples /// ``` /// use awc::Client; /// /// #[actix_rt::main] /// async fn main() { /// let mut client = Client::default(); /// /// let res = client.get("http://www.rust-lang.org") /// .insert_header(("User-Agent", "my-app/1.2")) /// .send() /// .await; /// /// println!("Response: {:?}", res); /// } /// ``` #[derive(Clone)] pub struct Client(pub(crate) ClientConfig); #[derive(Clone)] pub(crate) struct ClientConfig { pub(crate) connector: BoxConnectorService, pub(crate) default_headers: Rc<HeaderMap>, pub(crate) timeout: Option<Duration>, } impl Default for Client { fn default() -> Self { ClientBuilder::new().finish() } } impl Client { /// Constructs new client instance with default settings. pub fn new() -> Client { Client::default() } /// Constructs new `Client` builder. /// /// This function is equivalent of `ClientBuilder::new()`. pub fn builder() -> ClientBuilder< impl Service< ConnectInfo<Uri>, Response = TcpConnection<Uri, TcpStream>, Error = TcpConnectError, > + Clone, > { ClientBuilder::new() } /// Construct HTTP request. pub fn request<U>(&self, method: Method, url: U) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { let mut req = ClientRequest::new(method, url, self.0.clone()); for header in self.0.default_headers.iter() { req = req.append_header(header); } req } /// Create `ClientRequest` from `RequestHead` /// /// It is useful for proxy requests. This implementation /// copies all headers and the method. pub fn request_from<U>(&self, url: U, head: &RequestHead) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { let mut req = self.request(head.method.clone(), url); for header in head.headers.iter() { req = req.insert_header_if_none(header); } req } /// Construct HTTP *GET* request. pub fn get<U>(&self, url: U) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { self.request(Method::GET, url) } /// Construct HTTP *HEAD* request. pub fn head<U>(&self, url: U) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { self.request(Method::HEAD, url) } /// Construct HTTP *PUT* request. pub fn put<U>(&self, url: U) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { self.request(Method::PUT, url) } /// Construct HTTP *POST* request. pub fn post<U>(&self, url: U) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { self.request(Method::POST, url) } /// Construct HTTP *PATCH* request. pub fn patch<U>(&self, url: U) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { self.request(Method::PATCH, url) } /// Construct HTTP *DELETE* request. pub fn delete<U>(&self, url: U) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { self.request(Method::DELETE, url) } /// Construct HTTP *OPTIONS* request. pub fn options<U>(&self, url: U) -> ClientRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { self.request(Method::OPTIONS, url) } /// Initialize a WebSocket connection. /// Returns a WebSocket connection builder. pub fn ws<U>(&self, url: U) -> ws::WebsocketsRequest where Uri: TryFrom<U>, <Uri as TryFrom<U>>::Error: Into<HttpError>, { let mut req = ws::WebsocketsRequest::new(url, self.0.clone()); for (key, value) in self.0.default_headers.iter() { req.head.headers.insert(key.clone(), value.clone()); } req } /// Get default HeaderMap of Client. /// /// Returns Some(&mut HeaderMap) when Client object is unique /// (No other clone of client exists at the same time). pub fn headers(&mut self) -> Option<&mut HeaderMap> { Rc::get_mut(&mut self.0.default_headers) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/client/pool.rs
awc/src/client/pool.rs
//! Client connection pooling keyed on the authority part of the connection URI. use std::{ cell::RefCell, collections::{HashMap, VecDeque}, future::Future, io, ops::Deref, pin::Pin, rc::Rc, sync::Arc, task::{Context, Poll}, time::{Duration, Instant}, }; use actix_codec::{AsyncRead, AsyncWrite, ReadBuf}; use actix_http::Protocol; use actix_rt::time::{sleep, Sleep}; use actix_service::Service; use futures_core::future::LocalBoxFuture; use futures_util::FutureExt as _; use http::uri::Authority; use pin_project_lite::pin_project; use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use super::{ config::ConnectorConfig, connection::{ConnectionInnerType, ConnectionIo, ConnectionType, H2ConnectionInner}, error::ConnectError, h2proto::handshake, Connect, }; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Key { authority: Authority, } impl From<Authority> for Key { fn from(authority: Authority) -> Key { Key { authority } } } /// Connections pool to reuse I/O per [`Authority`]. #[doc(hidden)] pub struct ConnectionPool<S, Io> where Io: AsyncWrite + Unpin + 'static, { connector: S, inner: ConnectionPoolInner<Io>, } /// Wrapper type for check the ref count of Rc. pub struct ConnectionPoolInner<Io>(Rc<ConnectionPoolInnerPriv<Io>>) where Io: AsyncWrite + Unpin + 'static; impl<Io> ConnectionPoolInner<Io> where Io: AsyncWrite + Unpin + 'static, { fn new(config: ConnectorConfig) -> Self { let permits = Arc::new(Semaphore::new(config.limit)); let available = RefCell::new(HashMap::new()); Self(Rc::new(ConnectionPoolInnerPriv { config, available, permits, })) } /// Spawns a graceful shutdown task for the underlying I/O with a timeout. fn close(&self, conn: ConnectionInnerType<Io>) { if let Some(timeout) = self.config.disconnect_timeout { if let ConnectionInnerType::H1(io) = conn { if tokio::runtime::Handle::try_current().is_ok() { actix_rt::spawn(CloseConnection::new(io, timeout)); } } } } } impl<Io> Clone for ConnectionPoolInner<Io> where Io: AsyncWrite + Unpin + 'static, { fn clone(&self) -> Self { Self(Rc::clone(&self.0)) } } impl<Io> Deref for ConnectionPoolInner<Io> where Io: AsyncWrite + Unpin + 'static, { type Target = ConnectionPoolInnerPriv<Io>; fn deref(&self) -> &Self::Target { &self.0 } } impl<Io> Drop for ConnectionPoolInner<Io> where Io: AsyncWrite + Unpin + 'static, { fn drop(&mut self) { // When strong count is one it means the pool is dropped // remove and drop all Io types. if Rc::strong_count(&self.0) == 1 { self.permits.close(); std::mem::take(&mut *self.available.borrow_mut()) .into_iter() .for_each(|(_, conns)| { conns.into_iter().for_each(|pooled| self.close(pooled.conn)) }); } } } pub struct ConnectionPoolInnerPriv<Io> where Io: AsyncWrite + Unpin + 'static, { config: ConnectorConfig, available: RefCell<HashMap<Key, VecDeque<PooledConnection<Io>>>>, permits: Arc<Semaphore>, } impl<S, Io> ConnectionPool<S, Io> where Io: AsyncWrite + Unpin + 'static, { /// Construct a new connection pool. /// /// [`super::config::ConnectorConfig`]'s `limit` is used as the max permits allowed for /// in-flight connections. /// /// The pool can only have equal to `limit` amount of requests spawning/using Io type /// concurrently. /// /// Any requests beyond limit would be wait in fifo order and get notified in async manner /// by [`tokio::sync::Semaphore`] pub(crate) fn new(connector: S, config: ConnectorConfig) -> Self { let inner = ConnectionPoolInner::new(config); Self { connector, inner } } } impl<S, Io> Service<Connect> for ConnectionPool<S, Io> where S: Service<Connect, Response = (Io, Protocol), Error = ConnectError> + Clone + 'static, Io: ConnectionIo, { type Response = ConnectionType<Io>; type Error = ConnectError; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_service::forward_ready!(connector); fn call(&self, req: Connect) -> Self::Future { let connector = self.connector.clone(); let inner = self.inner.clone(); Box::pin(async move { let key = if let Some(authority) = req.uri.authority() { authority.clone().into() } else { return Err(ConnectError::Unresolved); }; // acquire an owned permit and carry it with connection let permit = Arc::clone(&inner.permits) .acquire_owned() .await .map_err(|_| { ConnectError::Io(io::Error::other( "Failed to acquire semaphore on client connection pool", )) })?; let conn = { let mut conn = None; // check if there is idle connection for given key. let mut map = inner.available.borrow_mut(); if let Some(conns) = map.get_mut(&key) { let now = Instant::now(); while let Some(mut c) = conns.pop_front() { let config = &inner.config; let idle_dur = now - c.used; let age = now - c.created; let conn_ineligible = idle_dur > config.conn_keep_alive || age > config.conn_lifetime; if conn_ineligible { // drop connections that are too old inner.close(c.conn); } else { // check if the connection is still usable if let ConnectionInnerType::H1(ref mut io) = c.conn { let check = ConnectionCheckFuture { io }; match check.now_or_never().expect( "ConnectionCheckFuture must never yield with Poll::Pending.", ) { ConnectionState::Tainted => { inner.close(c.conn); continue; } ConnectionState::Skip => continue, ConnectionState::Live => conn = Some(c), } } else { conn = Some(c); } break; } } }; conn }; // construct acquired. It's used to put Io type back to pool/ close the Io type. // permit is carried with the whole lifecycle of Acquired. let acquired = Acquired { key, inner, permit }; // match the connection and spawn new one if did not get anything. match conn { Some(conn) => Ok(ConnectionType::from_pool(conn.conn, conn.created, acquired)), None => { let (io, proto) = connector.call(req).await?; // NOTE: remove when http3 is added in support. assert!(proto != Protocol::Http3); if proto == Protocol::Http1 { Ok(ConnectionType::from_h1(io, Instant::now(), acquired)) } else { let config = &acquired.inner.config; let (sender, connection) = handshake(io, config).await?; let inner = H2ConnectionInner::new(sender, connection); Ok(ConnectionType::from_h2(inner, Instant::now(), acquired)) } } } }) } } /// Type for check the connection and determine if it's usable. struct ConnectionCheckFuture<'a, Io> { io: &'a mut Io, } enum ConnectionState { /// IO is pending and a new request would wake it. Live, /// IO unexpectedly has unread data and should be dropped. Tainted, /// IO should be skipped but not dropped. Skip, } impl<Io> Future for ConnectionCheckFuture<'_, Io> where Io: AsyncRead + Unpin, { type Output = ConnectionState; // this future is only used to get access to Context. // It should never return Poll::Pending. fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); let mut buf = [0; 2]; let mut read_buf = ReadBuf::new(&mut buf); let state = match Pin::new(&mut this.io).poll_read(cx, &mut read_buf) { Poll::Ready(Ok(())) if !read_buf.filled().is_empty() => ConnectionState::Tainted, Poll::Pending => ConnectionState::Live, _ => ConnectionState::Skip, }; Poll::Ready(state) } } struct PooledConnection<Io> { conn: ConnectionInnerType<Io>, used: Instant, created: Instant, } pin_project! { #[project = CloseConnectionProj] struct CloseConnection<Io> { io: Io, #[pin] timeout: Sleep, } } impl<Io> CloseConnection<Io> where Io: AsyncWrite + Unpin, { fn new(io: Io, timeout: Duration) -> Self { CloseConnection { io, timeout: sleep(timeout), } } } impl<Io> Future for CloseConnection<Io> where Io: AsyncWrite + Unpin, { type Output = (); fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> { let this = self.project(); match this.timeout.poll(cx) { Poll::Ready(_) => Poll::Ready(()), Poll::Pending => Pin::new(this.io).poll_shutdown(cx).map(|_| ()), } } } pub struct Acquired<Io> where Io: AsyncWrite + Unpin + 'static, { /// authority key for identify connection. key: Key, /// handle to connection pool. inner: ConnectionPoolInner<Io>, /// permit for limit concurrent in-flight connection for a Client object. permit: OwnedSemaphorePermit, } impl<Io: ConnectionIo> Acquired<Io> { /// Close the IO. pub(super) fn close(&self, conn: ConnectionInnerType<Io>) { self.inner.close(conn); } /// Release IO back into pool. pub(super) fn release(&self, conn: ConnectionInnerType<Io>, created: Instant) { let Acquired { key, inner, .. } = self; inner .available .borrow_mut() .entry(key.clone()) .or_insert_with(VecDeque::new) .push_back(PooledConnection { conn, created, used: Instant::now(), }); let _ = &self.permit; } } #[cfg(test)] mod test { use std::cell::Cell; use http::Uri; use super::*; /// A stream type that always returns pending on async read. /// /// Mocks an idle TCP stream that is ready to be used for client connections. struct TestStream(Rc<Cell<usize>>); impl Drop for TestStream { fn drop(&mut self) { self.0.set(self.0.get() - 1); } } impl AsyncRead for TestStream { fn poll_read( self: Pin<&mut Self>, _: &mut Context<'_>, _: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> { Poll::Pending } } impl AsyncWrite for TestStream { fn poll_write( self: Pin<&mut Self>, _: &mut Context<'_>, _: &[u8], ) -> Poll<io::Result<usize>> { unimplemented!() } fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { unimplemented!() } fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> { Poll::Ready(Ok(())) } } #[derive(Clone)] struct TestPoolConnector { generated: Rc<Cell<usize>>, } impl Service<Connect> for TestPoolConnector { type Response = (TestStream, Protocol); type Error = ConnectError; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, _: Connect) -> Self::Future { self.generated.set(self.generated.get() + 1); let generated = self.generated.clone(); Box::pin(async { Ok((TestStream(generated), Protocol::Http1)) }) } } fn release<T>(conn: ConnectionType<T>) where T: AsyncRead + AsyncWrite + Unpin + 'static, { match conn { ConnectionType::H1(mut conn) => conn.on_release(true), ConnectionType::H2(mut conn) => conn.on_release(false), } } #[actix_rt::test] async fn test_pool_limit() { let connector = TestPoolConnector { generated: Rc::new(Cell::new(0)), }; let config = ConnectorConfig { limit: 1, ..Default::default() }; let pool = super::ConnectionPool::new(connector, config); let req = Connect { uri: Uri::from_static("http://localhost"), addr: None, }; let conn = pool.call(req.clone()).await.unwrap(); let waiting = Rc::new(Cell::new(true)); let waiting_clone = waiting.clone(); actix_rt::spawn(async move { actix_rt::time::sleep(Duration::from_millis(100)).await; waiting_clone.set(false); drop(conn); }); assert!(waiting.get()); let now = Instant::now(); let conn = pool.call(req).await.unwrap(); release(conn); assert!(!waiting.get()); assert!(now.elapsed() >= Duration::from_millis(100)); } #[actix_rt::test] async fn test_pool_keep_alive() { let generated = Rc::new(Cell::new(0)); let generated_clone = generated.clone(); let connector = TestPoolConnector { generated }; let config = ConnectorConfig { conn_keep_alive: Duration::from_secs(1), ..Default::default() }; let pool = super::ConnectionPool::new(connector, config); let req = Connect { uri: Uri::from_static("http://localhost"), addr: None, }; let conn = pool.call(req.clone()).await.unwrap(); assert_eq!(1, generated_clone.get()); release(conn); let conn = pool.call(req.clone()).await.unwrap(); assert_eq!(1, generated_clone.get()); release(conn); actix_rt::time::sleep(Duration::from_millis(1500)).await; actix_rt::task::yield_now().await; let conn = pool.call(req).await.unwrap(); // Note: spawned recycle connection is not ran yet. // This is tokio current thread runtime specific behavior. assert_eq!(2, generated_clone.get()); // yield task so the old connection is properly dropped. actix_rt::task::yield_now().await; assert_eq!(1, generated_clone.get()); release(conn); } #[actix_rt::test] async fn test_pool_lifetime() { let generated = Rc::new(Cell::new(0)); let generated_clone = generated.clone(); let connector = TestPoolConnector { generated }; let config = ConnectorConfig { conn_lifetime: Duration::from_secs(1), ..Default::default() }; let pool = super::ConnectionPool::new(connector, config); let req = Connect { uri: Uri::from_static("http://localhost"), addr: None, }; let conn = pool.call(req.clone()).await.unwrap(); assert_eq!(1, generated_clone.get()); release(conn); let conn = pool.call(req.clone()).await.unwrap(); assert_eq!(1, generated_clone.get()); release(conn); actix_rt::time::sleep(Duration::from_millis(1500)).await; actix_rt::task::yield_now().await; let conn = pool.call(req).await.unwrap(); // Note: spawned recycle connection is not ran yet. // This is tokio current thread runtime specific behavior. assert_eq!(2, generated_clone.get()); // yield task so the old connection is properly dropped. actix_rt::task::yield_now().await; assert_eq!(1, generated_clone.get()); release(conn); } #[actix_rt::test] async fn test_pool_authority_key() { let generated = Rc::new(Cell::new(0)); let generated_clone = generated.clone(); let connector = TestPoolConnector { generated }; let config = ConnectorConfig::default(); let pool = super::ConnectionPool::new(connector, config); let req = Connect { uri: Uri::from_static("https://crates.io"), addr: None, }; let conn = pool.call(req.clone()).await.unwrap(); assert_eq!(1, generated_clone.get()); release(conn); let conn = pool.call(req).await.unwrap(); assert_eq!(1, generated_clone.get()); release(conn); let req = Connect { uri: Uri::from_static("https://google.com"), addr: None, }; let conn = pool.call(req.clone()).await.unwrap(); assert_eq!(2, generated_clone.get()); release(conn); let conn = pool.call(req).await.unwrap(); assert_eq!(2, generated_clone.get()); release(conn); } #[actix_rt::test] async fn test_pool_drop() { let generated = Rc::new(Cell::new(0)); let generated_clone = generated.clone(); let connector = TestPoolConnector { generated }; let config = ConnectorConfig::default(); let pool = Rc::new(super::ConnectionPool::new(connector, config)); let req = Connect { uri: Uri::from_static("https://crates.io"), addr: None, }; let conn = pool.call(req.clone()).await.unwrap(); assert_eq!(1, generated_clone.get()); release(conn); let req = Connect { uri: Uri::from_static("https://google.com"), addr: None, }; let conn = pool.call(req.clone()).await.unwrap(); assert_eq!(2, generated_clone.get()); release(conn); let clone1 = pool.clone(); let clone2 = clone1.clone(); drop(clone2); for _ in 0..2 { actix_rt::task::yield_now().await; } assert_eq!(2, generated_clone.get()); drop(clone1); for _ in 0..2 { actix_rt::task::yield_now().await; } assert_eq!(2, generated_clone.get()); drop(pool); for _ in 0..2 { actix_rt::task::yield_now().await; } assert_eq!(0, generated_clone.get()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/client/h1proto.rs
awc/src/client/h1proto.rs
use std::{ io::Write, pin::Pin, task::{Context, Poll}, }; use actix_codec::Framed; use actix_http::{ body::{BodySize, MessageBody}, error::PayloadError, h1, header::{HeaderMap, TryIntoHeaderValue, EXPECT, HOST}, Payload, RequestHeadType, ResponseHead, StatusCode, }; use actix_utils::future::poll_fn; use bytes::{buf::BufMut, Bytes, BytesMut}; use futures_core::{ready, Stream}; use futures_util::SinkExt as _; use pin_project_lite::pin_project; use super::{ connection::{ConnectionIo, H1Connection}, error::{ConnectError, SendRequestError}, }; use crate::BoxError; pub(crate) async fn send_request<Io, B>( io: H1Connection<Io>, mut head: RequestHeadType, body: B, ) -> Result<(ResponseHead, Payload), SendRequestError> where Io: ConnectionIo, B: MessageBody, B::Error: Into<BoxError>, { // set request host header if !head.as_ref().headers.contains_key(HOST) && !head.extra_headers().iter().any(|h| h.contains_key(HOST)) { if let Some(host) = head.as_ref().uri.host() { let mut wrt = BytesMut::with_capacity(host.len() + 5).writer(); match head.as_ref().uri.port_u16() { None | Some(80) | Some(443) => write!(wrt, "{}", host)?, Some(port) => write!(wrt, "{}:{}", host, port)?, }; match wrt.get_mut().split().freeze().try_into_value() { Ok(value) => match head { RequestHeadType::Owned(ref mut head) => { head.headers.insert(HOST, value); } RequestHeadType::Rc(_, ref mut extra_headers) => { let headers = extra_headers.get_or_insert(HeaderMap::new()); headers.insert(HOST, value); } }, Err(err) => log::error!("Can not set HOST header {err}"), } } } // create Framed and prepare sending request let mut framed = Framed::new(io, h1::ClientCodec::default()); // Check EXPECT header and enable expect handle flag accordingly. // See https://datatracker.ietf.org/doc/html/rfc7231#section-5.1.1 let is_expect = if head.as_ref().headers.contains_key(EXPECT) { match body.size() { BodySize::None | BodySize::Sized(0) => { let keep_alive = framed.codec_ref().keep_alive(); framed.io_mut().on_release(keep_alive); // TODO: use a new variant or a new type better describing error violate // `Requirements for clients` session of above RFC return Err(SendRequestError::Connect(ConnectError::Disconnected)); } _ => true, } } else { false }; let mut pin_framed = Pin::new(&mut framed); // special handle for EXPECT request. let (do_send, mut res_head) = if is_expect { pin_framed.send((head, body.size()).into()).await?; let head = poll_fn(|cx| pin_framed.as_mut().poll_next(cx)) .await .ok_or(ConnectError::Disconnected)??; // return response head in case status code is not continue // and current head would be used as final response head. (head.status == StatusCode::CONTINUE, Some(head)) } else { pin_framed.feed((head, body.size()).into()).await?; (true, None) }; if do_send { // send request body match body.size() { BodySize::None | BodySize::Sized(0) => { poll_fn(|cx| pin_framed.as_mut().flush(cx)).await?; } _ => send_body(body, pin_framed.as_mut()).await?, }; // read response and init read body let head = poll_fn(|cx| pin_framed.as_mut().poll_next(cx)) .await .ok_or(ConnectError::Disconnected)??; res_head = Some(head); } let head = res_head.unwrap(); match pin_framed.codec_ref().message_type() { h1::MessageType::None => { let keep_alive = pin_framed.codec_ref().keep_alive(); pin_framed.io_mut().on_release(keep_alive); Ok((head, Payload::None)) } _ => Ok(( head, Payload::Stream { payload: Box::pin(PlStream::new(framed)), }, )), } } pub(crate) async fn open_tunnel<Io>( io: Io, head: RequestHeadType, ) -> Result<(ResponseHead, Framed<Io, h1::ClientCodec>), SendRequestError> where Io: ConnectionIo, { // create Framed and send request. let mut framed = Framed::new(io, h1::ClientCodec::default()); framed.send((head, BodySize::None).into()).await?; // read response head. let head = poll_fn(|cx| Pin::new(&mut framed).poll_next(cx)) .await .ok_or(ConnectError::Disconnected)??; Ok((head, framed)) } /// send request body to the peer pub(crate) async fn send_body<Io, B>( body: B, mut framed: Pin<&mut Framed<Io, h1::ClientCodec>>, ) -> Result<(), SendRequestError> where Io: ConnectionIo, B: MessageBody, B::Error: Into<BoxError>, { actix_rt::pin!(body); let mut eof = false; while !eof { while !eof && !framed.as_ref().is_write_buf_full() { match poll_fn(|cx| body.as_mut().poll_next(cx)).await { Some(Ok(chunk)) => { framed.as_mut().write(h1::Message::Chunk(Some(chunk)))?; } Some(Err(err)) => return Err(SendRequestError::Body(err.into())), None => { eof = true; framed.as_mut().write(h1::Message::Chunk(None))?; } } } if !framed.as_ref().is_write_buf_empty() { poll_fn(|cx| match framed.as_mut().flush(cx) { Poll::Ready(Ok(_)) => Poll::Ready(Ok(())), Poll::Ready(Err(err)) => Poll::Ready(Err(err)), Poll::Pending => { if !framed.as_ref().is_write_buf_full() { Poll::Ready(Ok(())) } else { Poll::Pending } } }) .await?; } } framed.get_mut().flush().await?; Ok(()) } pin_project! { pub(crate) struct PlStream<Io: ConnectionIo> { #[pin] framed: Framed<H1Connection<Io>, h1::ClientPayloadCodec>, } } impl<Io: ConnectionIo> PlStream<Io> { fn new(framed: Framed<H1Connection<Io>, h1::ClientCodec>) -> Self { let framed = framed.into_map_codec(|codec| codec.into_payload_codec()); PlStream { framed } } } impl<Io: ConnectionIo> Stream for PlStream<Io> { type Item = Result<Bytes, PayloadError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.project(); match ready!(this.framed.as_mut().next_item(cx)?) { Some(Some(chunk)) => Poll::Ready(Some(Ok(chunk))), Some(None) => { let keep_alive = this.framed.codec_ref().keep_alive(); this.framed.io_mut().on_release(keep_alive); Poll::Ready(None) } None => Poll::Ready(None), } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/responses/response_body.rs
awc/src/responses/response_body.rs
use std::{ future::Future, mem, pin::Pin, task::{Context, Poll}, }; use actix_http::{error::PayloadError, header, HttpMessage}; use bytes::Bytes; use futures_core::Stream; use pin_project_lite::pin_project; use super::{read_body::ReadBody, ResponseTimeout, DEFAULT_BODY_LIMIT}; use crate::ClientResponse; pin_project! { /// A `Future` that reads a body stream, resolving as [`Bytes`]. /// /// # Errors /// `Future` implementation returns error if: /// - content type is not `application/json`; /// - content length is greater than [limit](JsonBody::limit) (default: 2 MiB). pub struct ResponseBody<S> { #[pin] body: Option<ReadBody<S>>, length: Option<usize>, timeout: ResponseTimeout, err: Option<PayloadError>, } } #[deprecated(since = "3.0.0", note = "Renamed to `ResponseBody`.")] pub type MessageBody<B> = ResponseBody<B>; impl<S> ResponseBody<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { /// Creates a body stream reader from a response by taking its payload. pub fn new(res: &mut ClientResponse<S>) -> ResponseBody<S> { let length = match res.headers().get(&header::CONTENT_LENGTH) { Some(value) => { let len = value.to_str().ok().and_then(|s| s.parse::<usize>().ok()); match len { None => return Self::err(PayloadError::UnknownLength), len => len, } } None => None, }; ResponseBody { body: Some(ReadBody::new(res.take_payload(), DEFAULT_BODY_LIMIT)), length, timeout: mem::take(&mut res.timeout), err: None, } } /// Change max size limit of payload. /// /// The default limit is 2 MiB. pub fn limit(mut self, limit: usize) -> Self { if let Some(ref mut body) = self.body { body.limit = limit; } self } fn err(err: PayloadError) -> Self { ResponseBody { body: None, length: None, timeout: ResponseTimeout::default(), err: Some(err), } } } impl<S> Future for ResponseBody<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { type Output = Result<Bytes, PayloadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); if let Some(err) = this.err.take() { return Poll::Ready(Err(err)); } if let Some(len) = this.length.take() { let body = Option::as_ref(&this.body).unwrap(); if len > body.limit { return Poll::Ready(Err(PayloadError::Overflow)); } } this.timeout.poll_timeout(cx)?; this.body.as_pin_mut().unwrap().poll(cx) } } #[cfg(test)] mod tests { use static_assertions::assert_impl_all; use super::*; use crate::test::TestResponse; assert_impl_all!(ResponseBody<()>: Unpin); #[actix_rt::test] async fn read_body() { let mut req = TestResponse::with_header((header::CONTENT_LENGTH, "xxxx")).finish(); match req.body().await.err().unwrap() { PayloadError::UnknownLength => {} _ => unreachable!("error"), } let mut req = TestResponse::with_header((header::CONTENT_LENGTH, "10000000")).finish(); match req.body().await.err().unwrap() { PayloadError::Overflow => {} _ => unreachable!("error"), } let mut req = TestResponse::default() .set_payload(Bytes::from_static(b"test")) .finish(); assert_eq!(req.body().await.ok().unwrap(), Bytes::from_static(b"test")); let mut req = TestResponse::default() .set_payload(Bytes::from_static(b"11111111111111")) .finish(); match req.body().limit(5).await.err().unwrap() { PayloadError::Overflow => {} _ => unreachable!("error"), } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/responses/response.rs
awc/src/responses/response.rs
use std::{ cell::{Ref, RefCell, RefMut}, fmt, mem, pin::Pin, task::{Context, Poll}, time::{Duration, Instant}, }; use actix_http::{ error::PayloadError, header::HeaderMap, BoxedPayloadStream, Extensions, HttpMessage, Payload, ResponseHead, StatusCode, Version, }; use actix_rt::time::{sleep, Sleep}; use bytes::Bytes; use futures_core::Stream; use pin_project_lite::pin_project; use serde::de::DeserializeOwned; use super::{JsonBody, ResponseBody, ResponseTimeout}; #[cfg(feature = "cookies")] use crate::cookie::{Cookie, ParseError as CookieParseError}; pin_project! { /// Client Response pub struct ClientResponse<S = BoxedPayloadStream> { pub(crate) head: ResponseHead, #[pin] pub(crate) payload: Payload<S>, pub(crate) timeout: ResponseTimeout, pub(crate) extensions: RefCell<Extensions>, } } impl<S> ClientResponse<S> { /// Create new Request instance pub(crate) fn new(head: ResponseHead, payload: Payload<S>) -> Self { ClientResponse { head, payload, timeout: ResponseTimeout::default(), extensions: RefCell::new(Extensions::new()), } } #[inline] pub(crate) fn head(&self) -> &ResponseHead { &self.head } /// Read the Request Version. #[inline] pub fn version(&self) -> Version { self.head().version } /// Get the status from the server. #[inline] pub fn status(&self) -> StatusCode { self.head().status } #[inline] /// Returns request's headers. pub fn headers(&self) -> &HeaderMap { &self.head().headers } /// Map the current body type to another using a closure. Returns a new response. /// /// Closure receives the response head and the current body type. pub fn map_body<F, U>(mut self, f: F) -> ClientResponse<U> where F: FnOnce(&mut ResponseHead, Payload<S>) -> Payload<U>, { let payload = f(&mut self.head, self.payload); ClientResponse { payload, head: self.head, timeout: self.timeout, extensions: self.extensions, } } /// Set a timeout duration for [`ClientResponse`](self::ClientResponse). /// /// This duration covers the duration of processing the response body stream /// and would end it as timeout error when deadline met. /// /// Disabled by default. pub fn timeout(self, dur: Duration) -> Self { let timeout = match self.timeout { ResponseTimeout::Disabled(Some(mut timeout)) | ResponseTimeout::Enabled(mut timeout) => match Instant::now().checked_add(dur) { Some(deadline) => { timeout.as_mut().reset(deadline.into()); ResponseTimeout::Enabled(timeout) } None => ResponseTimeout::Enabled(Box::pin(sleep(dur))), }, _ => ResponseTimeout::Enabled(Box::pin(sleep(dur))), }; Self { payload: self.payload, head: self.head, timeout, extensions: self.extensions, } } /// This method does not enable timeout. It's used to pass the boxed `Sleep` from /// `SendClientRequest` and reuse it's heap allocation together with it's slot in /// timer wheel. pub(crate) fn _timeout(mut self, timeout: Option<Pin<Box<Sleep>>>) -> Self { self.timeout = ResponseTimeout::Disabled(timeout); self } /// Load request cookies. #[cfg(feature = "cookies")] pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> { struct Cookies(Vec<Cookie<'static>>); if self.extensions().get::<Cookies>().is_none() { let mut cookies = Vec::new(); for hdr in self.headers().get_all(&actix_http::header::SET_COOKIE) { let s = std::str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?; cookies.push(Cookie::parse_encoded(s)?.into_owned()); } self.extensions_mut().insert(Cookies(cookies)); } Ok(Ref::map(self.extensions(), |ext| { &ext.get::<Cookies>().unwrap().0 })) } /// Return request cookie. #[cfg(feature = "cookies")] pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> { if let Ok(cookies) = self.cookies() { for cookie in cookies.iter() { if cookie.name() == name { return Some(cookie.to_owned()); } } } None } } impl<S> ClientResponse<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { /// Returns a [`Future`] that consumes the body stream and resolves to [`Bytes`]. /// /// # Errors /// `Future` implementation returns error if: /// - content length is greater than [limit](ResponseBody::limit) (default: 2 MiB) /// /// # Examples /// ```no_run /// # use awc::Client; /// # use bytes::Bytes; /// # #[actix_rt::main] /// # async fn async_ctx() -> Result<(), Box<dyn std::error::Error>> { /// let client = Client::default(); /// let mut res = client.get("https://httpbin.org/robots.txt").send().await?; /// let body: Bytes = res.body().await?; /// # Ok(()) /// # } /// ``` /// /// [`Future`]: std::future::Future pub fn body(&mut self) -> ResponseBody<S> { ResponseBody::new(self) } /// Returns a [`Future`] consumes the body stream, parses JSON, and resolves to a deserialized /// `T` value. /// /// # Errors /// Future returns error if: /// - content type is not `application/json`; /// - content length is greater than [limit](JsonBody::limit) (default: 2 MiB). /// /// # Examples /// ```no_run /// # use awc::Client; /// # #[actix_rt::main] /// # async fn async_ctx() -> Result<(), Box<dyn std::error::Error>> { /// let client = Client::default(); /// let mut res = client.get("https://httpbin.org/json").send().await?; /// let val = res.json::<serde_json::Value>().await?; /// assert!(val.is_object()); /// # Ok(()) /// # } /// ``` /// /// [`Future`]: std::future::Future pub fn json<T: DeserializeOwned>(&mut self) -> JsonBody<S, T> { JsonBody::new(self) } } impl<S> fmt::Debug for ClientResponse<S> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!(f, "\nClientResponse {:?} {}", self.version(), self.status(),)?; writeln!(f, " headers:")?; for (key, val) in self.headers().iter() { writeln!(f, " {:?}: {:?}", key, val)?; } Ok(()) } } impl<S> HttpMessage for ClientResponse<S> { type Stream = S; fn headers(&self) -> &HeaderMap { &self.head.headers } fn take_payload(&mut self) -> Payload<S> { mem::replace(&mut self.payload, Payload::None) } fn extensions(&self) -> Ref<'_, Extensions> { self.extensions.borrow() } fn extensions_mut(&self) -> RefMut<'_, Extensions> { self.extensions.borrow_mut() } } impl<S> Stream for ClientResponse<S> where S: Stream<Item = Result<Bytes, PayloadError>> + Unpin, { type Item = Result<Bytes, PayloadError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.project(); this.timeout.poll_timeout(cx)?; this.payload.poll_next(cx) } } #[cfg(test)] mod tests { use static_assertions::assert_impl_all; use super::*; use crate::any_body::AnyBody; assert_impl_all!(ClientResponse: Unpin); assert_impl_all!(ClientResponse<()>: Unpin); assert_impl_all!(ClientResponse<AnyBody>: Unpin); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/responses/json_body.rs
awc/src/responses/json_body.rs
use std::{ future::Future, marker::PhantomData, mem, pin::Pin, task::{Context, Poll}, }; use actix_http::{error::PayloadError, header, HttpMessage}; use bytes::Bytes; use futures_core::{ready, Stream}; use pin_project_lite::pin_project; use serde::de::DeserializeOwned; use super::{read_body::ReadBody, ResponseTimeout, DEFAULT_BODY_LIMIT}; use crate::{error::JsonPayloadError, ClientResponse}; pin_project! { /// A `Future` that reads a body stream, parses JSON, resolving to a deserialized `T`. /// /// # Errors /// `Future` implementation returns error if: /// - content type is not `application/json`; /// - content length is greater than [limit](JsonBody::limit) (default: 2 MiB). pub struct JsonBody<S, T> { #[pin] body: Option<ReadBody<S>>, length: Option<usize>, timeout: ResponseTimeout, err: Option<JsonPayloadError>, _phantom: PhantomData<T>, } } impl<S, T> JsonBody<S, T> where S: Stream<Item = Result<Bytes, PayloadError>>, T: DeserializeOwned, { /// Creates a JSON body stream reader from a response by taking its payload. pub fn new(res: &mut ClientResponse<S>) -> Self { // check content-type let json = if let Ok(Some(mime)) = res.mime_type() { mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON) } else { false }; if !json { return JsonBody { length: None, body: None, timeout: ResponseTimeout::default(), err: Some(JsonPayloadError::ContentType), _phantom: PhantomData, }; } let length = res .headers() .get(&header::CONTENT_LENGTH) .and_then(|len_hdr| len_hdr.to_str().ok()) .and_then(|len_str| len_str.parse::<usize>().ok()); JsonBody { body: Some(ReadBody::new(res.take_payload(), DEFAULT_BODY_LIMIT)), length, timeout: mem::take(&mut res.timeout), err: None, _phantom: PhantomData, } } /// Change max size of payload. Default limit is 2 MiB. pub fn limit(mut self, limit: usize) -> Self { if let Some(ref mut fut) = self.body { fut.limit = limit; } self } } impl<S, T> Future for JsonBody<S, T> where S: Stream<Item = Result<Bytes, PayloadError>>, T: DeserializeOwned, { type Output = Result<T, JsonPayloadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); if let Some(err) = this.err.take() { return Poll::Ready(Err(err)); } if let Some(len) = this.length.take() { let body = Option::as_ref(&this.body).unwrap(); if len > body.limit { return Poll::Ready(Err(JsonPayloadError::Payload(PayloadError::Overflow))); } } this.timeout .poll_timeout(cx) .map_err(JsonPayloadError::Payload)?; let body = ready!(this.body.as_pin_mut().unwrap().poll(cx))?; Poll::Ready(serde_json::from_slice::<T>(&body).map_err(JsonPayloadError::from)) } } #[cfg(test)] mod tests { use actix_http::BoxedPayloadStream; use serde::{Deserialize, Serialize}; use static_assertions::assert_impl_all; use super::*; use crate::test::TestResponse; assert_impl_all!(JsonBody<BoxedPayloadStream, String>: Unpin); #[derive(Serialize, Deserialize, PartialEq, Debug)] struct MyObject { name: String, } fn json_eq(err: JsonPayloadError, other: JsonPayloadError) -> bool { match err { JsonPayloadError::Payload(PayloadError::Overflow) => { matches!(other, JsonPayloadError::Payload(PayloadError::Overflow)) } JsonPayloadError::ContentType => matches!(other, JsonPayloadError::ContentType), _ => false, } } #[actix_rt::test] async fn read_json_body() { let mut req = TestResponse::default().finish(); let json = JsonBody::<_, MyObject>::new(&mut req).await; assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); let mut req = TestResponse::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/text"), )) .finish(); let json = JsonBody::<_, MyObject>::new(&mut req).await; assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); let mut req = TestResponse::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("10000"), )) .finish(); let json = JsonBody::<_, MyObject>::new(&mut req).limit(100).await; assert!(json_eq( json.err().unwrap(), JsonPayloadError::Payload(PayloadError::Overflow) )); let mut req = TestResponse::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .finish(); let json = JsonBody::<_, MyObject>::new(&mut req).await; assert_eq!( json.ok().unwrap(), MyObject { name: "test".to_owned() } ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/responses/mod.rs
awc/src/responses/mod.rs
use std::{future::Future, io, pin::Pin, task::Context}; use actix_http::error::PayloadError; use actix_rt::time::Sleep; mod json_body; mod read_body; mod response; mod response_body; #[allow(deprecated)] pub use self::response_body::{MessageBody, ResponseBody}; pub use self::{json_body::JsonBody, response::ClientResponse}; /// Default body size limit: 2 MiB const DEFAULT_BODY_LIMIT: usize = 2 * 1024 * 1024; /// Helper enum with reusable sleep passed from `SendClientResponse`. /// /// See [`ClientResponse::_timeout`] for reason. pub(crate) enum ResponseTimeout { Disabled(Option<Pin<Box<Sleep>>>), Enabled(Pin<Box<Sleep>>), } impl Default for ResponseTimeout { fn default() -> Self { Self::Disabled(None) } } impl ResponseTimeout { fn poll_timeout(&mut self, cx: &mut Context<'_>) -> Result<(), PayloadError> { match *self { Self::Enabled(ref mut timeout) => { if timeout.as_mut().poll(cx).is_ready() { Err(PayloadError::Io(io::Error::new( io::ErrorKind::TimedOut, "Response Payload IO timed out", ))) } else { Ok(()) } } Self::Disabled(_) => Ok(()), } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/src/responses/read_body.rs
awc/src/responses/read_body.rs
use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use actix_http::{error::PayloadError, Payload}; use bytes::{Bytes, BytesMut}; use futures_core::{ready, Stream}; use pin_project_lite::pin_project; pin_project! { pub(crate) struct ReadBody<S> { #[pin] pub(crate) stream: Payload<S>, pub(crate) buf: BytesMut, pub(crate) limit: usize, } } impl<S> ReadBody<S> { pub(crate) fn new(stream: Payload<S>, limit: usize) -> Self { Self { stream, buf: BytesMut::new(), limit, } } } impl<S> Future for ReadBody<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { type Output = Result<Bytes, PayloadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.project(); while let Some(chunk) = ready!(this.stream.as_mut().poll_next(cx)?) { if (this.buf.len() + chunk.len()) > *this.limit { return Poll::Ready(Err(PayloadError::Overflow)); } this.buf.extend_from_slice(&chunk); } Poll::Ready(Ok(this.buf.split().freeze())) } } #[cfg(test)] mod tests { use static_assertions::assert_impl_all; use super::*; use crate::any_body::AnyBody; assert_impl_all!(ReadBody<()>: Unpin); assert_impl_all!(ReadBody<AnyBody>: Unpin); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/tests/test_ssl_client.rs
awc/tests/test_ssl_client.rs
#![cfg(feature = "openssl")] extern crate tls_openssl as openssl; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use actix_http::HttpService; use actix_http_test::test_server; use actix_service::{fn_service, map_config, ServiceFactoryExt}; use actix_utils::future::ok; use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse}; use openssl::{ pkey::PKey, ssl::{SslAcceptor, SslConnector, SslMethod, SslVerifyMode}, x509::X509, }; fn tls_config() -> SslAcceptor { let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(["localhost".to_owned()]).unwrap(); let cert_file = cert.pem(); let key_file = key_pair.serialize_pem(); let cert = X509::from_pem(cert_file.as_bytes()).unwrap(); let key = PKey::private_key_from_pem(key_file.as_bytes()).unwrap(); let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); builder.set_certificate(&cert).unwrap(); builder.set_private_key(&key).unwrap(); builder.set_alpn_select_callback(|_, protos| { const H2: &[u8] = b"\x02h2"; if protos.windows(3).any(|window| window == H2) { Ok(b"h2") } else { Err(openssl::ssl::AlpnError::NOACK) } }); builder.set_alpn_protos(b"\x02h2").unwrap(); builder.build() } #[actix_rt::test] async fn test_connection_reuse_h2() { let num = Arc::new(AtomicUsize::new(0)); let num2 = num.clone(); let srv = test_server(move || { let num2 = num2.clone(); fn_service(move |io| { num2.fetch_add(1, Ordering::Relaxed); ok(io) }) .and_then( HttpService::build() .h2(map_config( App::new().service(web::resource("/").route(web::to(HttpResponse::Ok))), |_| AppConfig::default(), )) .openssl(tls_config()) .map_err(|_| ()), ) }) .await; // disable ssl verification let mut builder = SslConnector::builder(SslMethod::tls()).unwrap(); builder.set_verify(SslVerifyMode::NONE); let _ = builder .set_alpn_protos(b"\x02h2\x08http/1.1") .map_err(|e| log::error!("Can not set alpn protocol: {:?}", e)); let client = awc::Client::builder() .connector(awc::Connector::new().openssl(builder.build())) .finish(); // req 1 let request = client.get(srv.surl("/")).send(); let response = request.await.unwrap(); assert!(response.status().is_success()); // req 2 let req = client.post(srv.surl("/")); let response = req.send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.version(), Version::HTTP_2); // one connection assert_eq!(num.load(Ordering::Relaxed), 1); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/tests/test_rustls_client.rs
awc/tests/test_rustls_client.rs
#![cfg(feature = "rustls-0_23-webpki-roots")] extern crate tls_rustls_0_23 as rustls; use std::sync::{ atomic::{AtomicUsize, Ordering}, Arc, }; use actix_http::HttpService; use actix_http_test::test_server; use actix_service::{fn_service, map_config, ServiceFactoryExt}; use actix_tls::connect::rustls_0_23::webpki_roots_cert_store; use actix_utils::future::ok; use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse}; use rustls::{pki_types::ServerName, ClientConfig, ServerConfig}; use rustls_pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; fn tls_config() -> ServerConfig { let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(["localhost".to_owned()]).unwrap(); let cert_chain = vec![cert.der().clone()]; let key_der = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der())); ServerConfig::builder() .with_no_client_auth() .with_single_cert(cert_chain, key_der) .unwrap() } mod danger { use rustls::{ client::danger::{ServerCertVerified, ServerCertVerifier}, pki_types::UnixTime, }; use super::*; #[derive(Debug)] pub struct NoCertificateVerification; impl ServerCertVerifier for NoCertificateVerification { fn verify_server_cert( &self, _end_entity: &CertificateDer<'_>, _intermediates: &[CertificateDer<'_>], _server_name: &ServerName<'_>, _ocsp_response: &[u8], _now: UnixTime, ) -> Result<ServerCertVerified, rustls::Error> { Ok(rustls::client::danger::ServerCertVerified::assertion()) } fn verify_tls12_signature( &self, _message: &[u8], _cert: &CertificateDer<'_>, _dss: &rustls::DigitallySignedStruct, ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> { Ok(rustls::client::danger::HandshakeSignatureValid::assertion()) } fn verify_tls13_signature( &self, _message: &[u8], _cert: &CertificateDer<'_>, _dss: &rustls::DigitallySignedStruct, ) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> { Ok(rustls::client::danger::HandshakeSignatureValid::assertion()) } fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> { rustls::crypto::aws_lc_rs::default_provider() .signature_verification_algorithms .supported_schemes() } } } #[actix_rt::test] async fn test_connection_reuse_h2() { let num = Arc::new(AtomicUsize::new(0)); let num2 = num.clone(); let srv = test_server(move || { let num2 = num2.clone(); fn_service(move |io| { num2.fetch_add(1, Ordering::Relaxed); ok(io) }) .and_then( HttpService::build() .h2(map_config( App::new().service(web::resource("/").route(web::to(HttpResponse::Ok))), |_| AppConfig::default(), )) .rustls_0_23(tls_config()) .map_err(|_| ()), ) }) .await; let mut config = ClientConfig::builder() .with_root_certificates(webpki_roots_cert_store()) .with_no_client_auth(); let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; config.alpn_protocols = protos; // disable TLS verification config .dangerous() .set_certificate_verifier(Arc::new(danger::NoCertificateVerification)); let client = awc::Client::builder() .connector(awc::Connector::new().rustls_0_23(Arc::new(config))) .finish(); // req 1 let request = client.get(srv.surl("/")).send(); let response = request.await.unwrap(); assert!(response.status().is_success()); // req 2 let req = client.post(srv.surl("/")); let response = req.send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.version(), Version::HTTP_2); // one connection assert_eq!(num.load(Ordering::Relaxed), 1); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/tests/test_client.rs
awc/tests/test_client.rs
use std::{ collections::HashMap, convert::Infallible, io::{Read, Write}, net::{IpAddr, Ipv4Addr}, sync::{ atomic::{AtomicUsize, Ordering}, Arc, }, time::Duration, }; use actix_http::{HttpService, StatusCode}; use actix_http_test::test_server; use actix_service::{fn_service, map_config, ServiceFactoryExt as _}; use actix_utils::future::ok; use actix_web::{dev::AppConfig, http::header, web, App, Error, HttpRequest, HttpResponse}; use awc::error::{JsonPayloadError, PayloadError, SendRequestError}; use base64::prelude::*; use bytes::Bytes; use cookie::Cookie; use futures_util::stream; use rand::distr::{Alphanumeric, SampleString as _}; mod utils; const S: &str = "Hello World "; const STR: &str = const_str::repeat!(S, 100); #[actix_rt::test] async fn simple() { let srv = actix_test::start(|| { App::new() .service(web::resource("/").route(web::to(|| async { HttpResponse::Ok().body(STR) }))) }); let request = srv.get("/").insert_header(("x-test", "111")).send(); let mut response = request.await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); let mut response = srv.post("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); // camel case let response = srv.post("/").camel_case().send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn json() { let srv = actix_test::start(|| { App::new() .service(web::resource("/").route(web::to(|_: web::Json<String>| HttpResponse::Ok()))) }); let request = srv .get("/") .insert_header(("x-test", "111")) .send_json(&"TEST".to_string()); let response = request.await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn form() { let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to( |_: web::Form<HashMap<String, String>>| HttpResponse::Ok(), ))) }); let mut data = HashMap::new(); let _ = data.insert("key".to_string(), "TEST".to_string()); let request = srv .get("/") .append_header(("x-test", "111")) .send_form(&data); let response = request.await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn timeout() { let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|| async { actix_rt::time::sleep(Duration::from_millis(200)).await; HttpResponse::Ok().body(STR) }))) }); let connector = awc::Connector::new() .connector(actix_tls::connect::ConnectorService::default()) .timeout(Duration::from_secs(15)); let client = awc::Client::builder() .connector(connector) .timeout(Duration::from_millis(50)) .finish(); let request = client.get(srv.url("/")).send(); match request.await { Err(SendRequestError::Timeout) => {} _ => panic!(), } } #[actix_rt::test] async fn timeout_override() { let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|| async { actix_rt::time::sleep(Duration::from_millis(200)).await; HttpResponse::Ok().body(STR) }))) }); let client = awc::Client::builder() .timeout(Duration::from_millis(50000)) .finish(); let request = client .get(srv.url("/")) .timeout(Duration::from_millis(50)) .send(); match request.await { Err(SendRequestError::Timeout) => {} _ => panic!(), } } #[actix_rt::test] async fn response_timeout() { use futures_util::{stream::once, StreamExt as _}; let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|| async { Ok::<_, Error>( HttpResponse::Ok() .content_type("application/json") .streaming(Box::pin(once(async { actix_rt::time::sleep(Duration::from_millis(200)).await; Ok::<_, Error>(Bytes::from(STR)) }))), ) }))) }); let client = awc::Client::new(); let res = client .get(srv.url("/")) .send() .await .unwrap() .timeout(Duration::from_millis(500)) .body() .await .unwrap(); assert_eq!(std::str::from_utf8(res.as_ref()).unwrap(), STR); let res = client .get(srv.url("/")) .send() .await .unwrap() .timeout(Duration::from_millis(100)) .next() .await .unwrap(); match res { Err(PayloadError::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::TimedOut), _ => panic!("Response error type is not matched"), } let res = client .get(srv.url("/")) .send() .await .unwrap() .timeout(Duration::from_millis(100)) .body() .await; match res { Err(PayloadError::Io(e)) => assert_eq!(e.kind(), std::io::ErrorKind::TimedOut), _ => panic!("Response error type is not matched"), } let res = client .get(srv.url("/")) .send() .await .unwrap() .timeout(Duration::from_millis(100)) .json::<HashMap<String, String>>() .await; match res { Err(JsonPayloadError::Payload(PayloadError::Io(e))) => { assert_eq!(e.kind(), std::io::ErrorKind::TimedOut) } _ => panic!("Response error type is not matched"), } } #[actix_rt::test] async fn connection_reuse() { let num = Arc::new(AtomicUsize::new(0)); let num2 = num.clone(); let srv = test_server(move || { let num2 = num2.clone(); fn_service(move |io| { num2.fetch_add(1, Ordering::Relaxed); ok(io) }) .and_then( HttpService::new(map_config( App::new().service(web::resource("/").route(web::to(HttpResponse::Ok))), |_| AppConfig::default(), )) .tcp(), ) }) .await; let client = awc::Client::default(); // req 1 let request = client.get(srv.url("/")).send(); let response = request.await.unwrap(); assert!(response.status().is_success()); // req 2 let req = client.post(srv.url("/")); let response = req.send().await.unwrap(); assert!(response.status().is_success()); // one connection assert_eq!(num.load(Ordering::Relaxed), 1); } #[actix_rt::test] async fn connection_force_close() { let num = Arc::new(AtomicUsize::new(0)); let num2 = num.clone(); let srv = test_server(move || { let num2 = num2.clone(); fn_service(move |io| { num2.fetch_add(1, Ordering::Relaxed); ok(io) }) .and_then( HttpService::new(map_config( App::new().service(web::resource("/").route(web::to(HttpResponse::Ok))), |_| AppConfig::default(), )) .tcp(), ) }) .await; let client = awc::Client::default(); // req 1 let request = client.get(srv.url("/")).force_close().send(); let response = request.await.unwrap(); assert!(response.status().is_success()); // req 2 let req = client.post(srv.url("/")).force_close(); let response = req.send().await.unwrap(); assert!(response.status().is_success()); // two connection assert_eq!(num.load(Ordering::Relaxed), 2); } #[actix_rt::test] async fn connection_server_close() { let num = Arc::new(AtomicUsize::new(0)); let num2 = num.clone(); let srv = test_server(move || { let num2 = num2.clone(); fn_service(move |io| { num2.fetch_add(1, Ordering::Relaxed); ok(io) }) .and_then( HttpService::new(map_config( App::new().service(web::resource("/").route(web::to(|| async { HttpResponse::Ok().force_close().finish() }))), |_| AppConfig::default(), )) .tcp(), ) }) .await; let client = awc::Client::default(); // req 1 let request = client.get(srv.url("/")).send(); let response = request.await.unwrap(); assert!(response.status().is_success()); // req 2 let req = client.post(srv.url("/")); let response = req.send().await.unwrap(); assert!(response.status().is_success()); // two connection assert_eq!(num.load(Ordering::Relaxed), 2); } #[actix_rt::test] async fn connection_wait_queue() { let num = Arc::new(AtomicUsize::new(0)); let num2 = num.clone(); let srv = test_server(move || { let num2 = num2.clone(); fn_service(move |io| { num2.fetch_add(1, Ordering::Relaxed); ok(io) }) .and_then( HttpService::new(map_config( App::new().service( web::resource("/").route(web::to(|| async { HttpResponse::Ok().body(STR) })), ), |_| AppConfig::default(), )) .tcp(), ) }) .await; let client = awc::Client::builder() .connector(awc::Connector::new().limit(1)) .finish(); // req 1 let request = client.get(srv.url("/")).send(); let mut response = request.await.unwrap(); assert!(response.status().is_success()); // req 2 let req2 = client.post(srv.url("/")); let req2_fut = req2.send(); // read response 1 let bytes = response.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); // req 2 let response = req2_fut.await.unwrap(); assert!(response.status().is_success()); // two connection assert_eq!(num.load(Ordering::Relaxed), 1); } #[actix_rt::test] async fn connection_wait_queue_force_close() { let num = Arc::new(AtomicUsize::new(0)); let num2 = num.clone(); let srv = test_server(move || { let num2 = num2.clone(); fn_service(move |io| { num2.fetch_add(1, Ordering::Relaxed); ok(io) }) .and_then( HttpService::new(map_config( App::new().service(web::resource("/").route(web::to(|| async { HttpResponse::Ok().force_close().body(STR) }))), |_| AppConfig::default(), )) .tcp(), ) }) .await; let client = awc::Client::builder() .connector(awc::Connector::new().limit(1)) .finish(); // req 1 let request = client.get(srv.url("/")).send(); let mut response = request.await.unwrap(); assert!(response.status().is_success()); // req 2 let req2 = client.post(srv.url("/")); let req2_fut = req2.send(); // read response 1 let bytes = response.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); // req 2 let response = req2_fut.await.unwrap(); assert!(response.status().is_success()); // two connection assert_eq!(num.load(Ordering::Relaxed), 2); } #[actix_rt::test] async fn with_query_parameter() { let srv = actix_test::start(|| { App::new().service(web::resource("/").to(|req: HttpRequest| { if req.query_string().contains("qp") { HttpResponse::Ok() } else { HttpResponse::BadRequest() } })) }); let res = awc::Client::new() .get(srv.url("/?qp=5")) .send() .await .unwrap(); assert!(res.status().is_success()); } #[cfg(feature = "compress-gzip")] #[actix_rt::test] async fn no_decompress() { let srv = actix_test::start(|| { App::new() .wrap(actix_web::middleware::Compress::default()) .service(web::resource("/").route(web::to(|| async { HttpResponse::Ok().body(STR) }))) }); let mut res = awc::Client::new() .get(srv.url("/")) .insert_header((header::ACCEPT_ENCODING, "gzip")) .no_decompress() .send() .await .unwrap(); assert!(res.status().is_success()); // read response let bytes = res.body().await.unwrap(); assert_eq!(utils::gzip::decode(bytes), STR.as_bytes()); // POST let mut res = awc::Client::new() .post(srv.url("/")) .insert_header((header::ACCEPT_ENCODING, "gzip")) .no_decompress() .send() .await .unwrap(); assert!(res.status().is_success()); let bytes = res.body().await.unwrap(); assert_eq!(utils::gzip::decode(bytes), STR.as_bytes()); } #[cfg(feature = "compress-gzip")] #[actix_rt::test] async fn client_gzip_encoding() { let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|| async { HttpResponse::Ok() .insert_header(header::ContentEncoding::Gzip) .body(utils::gzip::encode(STR)) }))) }); // client request let mut response = srv.post("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, STR); } #[cfg(feature = "compress-gzip")] #[actix_rt::test] async fn client_gzip_encoding_large() { let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|| async { HttpResponse::Ok() .insert_header(header::ContentEncoding::Gzip) .body(utils::gzip::encode(STR.repeat(10))) }))) }); // client request let mut response = srv.post("/").send().await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, STR.repeat(10)); } #[cfg(feature = "compress-gzip")] #[actix_rt::test] async fn client_gzip_encoding_large_random() { let data = Alphanumeric.sample_string(&mut rand::rng(), 100_000); let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|data: Bytes| async { HttpResponse::Ok() .insert_header(header::ContentEncoding::Gzip) .body(utils::gzip::encode(data)) }))) }); // client request let mut response = srv.post("/").send_body(data.clone()).await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, data); } #[cfg(feature = "compress-brotli")] #[actix_rt::test] async fn client_brotli_encoding() { let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|data: Bytes| async { HttpResponse::Ok() .insert_header(("content-encoding", "br")) .body(utils::brotli::encode(data)) }))) }); // client request let mut response = srv.post("/").send_body(STR).await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[cfg(feature = "compress-brotli")] #[actix_rt::test] async fn client_brotli_encoding_large_random() { let data = Alphanumeric.sample_string(&mut rand::rng(), 70_000); let srv = actix_test::start(|| { App::new().service(web::resource("/").route(web::to(|data: Bytes| async { HttpResponse::Ok() .insert_header(header::ContentEncoding::Brotli) .body(utils::brotli::encode(data)) }))) }); // client request let mut response = srv.post("/").send_body(data.clone()).await.unwrap(); assert!(response.status().is_success()); // read response let bytes = response.body().await.unwrap(); assert_eq!(bytes, data); } #[actix_rt::test] async fn client_deflate_encoding() { let srv = actix_test::start(|| { App::new().default_service(web::to(|body: Bytes| async { HttpResponse::Ok().body(body) })) }); let req = srv .post("/") .insert_header((header::ACCEPT_ENCODING, "gzip")) .send_body(STR); let mut res = req.await.unwrap(); assert_eq!(res.status(), StatusCode::OK); let bytes = res.body().await.unwrap(); assert_eq!(bytes, STR); } #[actix_rt::test] async fn client_deflate_encoding_large_random() { let data = Alphanumeric.sample_string(&mut rand::rng(), 70_000); let srv = actix_test::start(|| { App::new().default_service(web::to(|body: Bytes| async { HttpResponse::Ok().body(body) })) }); let req = srv .post("/") .insert_header((header::ACCEPT_ENCODING, "br")) .send_body(data.clone()); let mut res = req.await.unwrap(); let bytes = res.body().await.unwrap(); assert_eq!(res.status(), StatusCode::OK); assert_eq!(bytes, Bytes::from(data)); } #[actix_rt::test] async fn client_streaming_explicit() { let srv = actix_test::start(|| { App::new().default_service(web::to(|body: web::Payload| async { HttpResponse::Ok().streaming(body) })) }); let body = stream::once(async { Ok::<_, actix_http::Error>(Bytes::from_static(STR.as_bytes())) }); let req = srv .post("/") .insert_header((header::ACCEPT_ENCODING, "identity")) .send_stream(Box::pin(body)); let mut res = req.await.unwrap(); assert!(res.status().is_success()); let bytes = res.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn body_streaming_implicit() { let srv = actix_test::start(|| { App::new().default_service(web::to(|| async { let body = stream::once(async { Ok::<_, Infallible>(Bytes::from_static(STR.as_bytes())) }); HttpResponse::Ok().streaming(body) })) }); let req = srv .get("/") .insert_header((header::ACCEPT_ENCODING, "gzip")) .send(); let mut res = req.await.unwrap(); assert!(res.status().is_success()); let bytes = res.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(STR.as_ref())); } #[actix_rt::test] async fn client_cookie_handling() { use std::io::{Error as IoError, ErrorKind}; let cookie1 = Cookie::build("cookie1", "value1").finish(); let cookie2 = Cookie::build("cookie2", "value2") .domain("www.example.org") .path("/") .secure(true) .http_only(true) .finish(); // Q: are all these clones really necessary? A: Yes, possibly let cookie1b = cookie1.clone(); let cookie2b = cookie2.clone(); let srv = actix_test::start(move || { let cookie1 = cookie1b.clone(); let cookie2 = cookie2b.clone(); App::new().route( "/", web::to(move |req: HttpRequest| { let cookie1 = cookie1.clone(); let cookie2 = cookie2.clone(); async move { // Check cookies were sent correctly req.cookie("cookie1") .ok_or(()) .and_then(|c1| { if c1.value() == "value1" { Ok(()) } else { Err(()) } }) .and_then(|()| req.cookie("cookie2").ok_or(())) .and_then(|c2| { if c2.value() == "value2" { Ok(()) } else { Err(()) } }) .map_err(|_| Error::from(IoError::from(ErrorKind::NotFound)))?; // Send some cookies back Ok::<_, Error>(HttpResponse::Ok().cookie(cookie1).cookie(cookie2).finish()) } }), ) }); let request = srv.get("/").cookie(cookie1.clone()).cookie(cookie2.clone()); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let c1 = response.cookie("cookie1").expect("Missing cookie1"); assert_eq!(c1, cookie1); let c2 = response.cookie("cookie2").expect("Missing cookie2"); assert_eq!(c2, cookie2); } #[actix_rt::test] async fn client_unread_response() { let addr = actix_test::unused_addr(); let lst = std::net::TcpListener::bind(addr).unwrap(); std::thread::spawn(move || { let (mut stream, _) = lst.accept().unwrap(); let mut b = [0; 1000]; let _ = stream.read(&mut b).unwrap(); let _ = stream.write_all( b"HTTP/1.1 200 OK\r\n\ connection: close\r\n\ \r\n\ welcome!", ); }); // client request let req = awc::Client::new().get(format!("http://{}/", addr).as_str()); let mut res = req.send().await.unwrap(); assert!(res.status().is_success()); // awc does not read all bytes unless content-length is specified let bytes = res.body().await.unwrap(); assert_eq!(bytes, Bytes::from_static(b"")); } #[actix_rt::test] async fn client_basic_auth() { let srv = actix_test::start(|| { App::new().route( "/", web::to(|req: HttpRequest| { if req .headers() .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap() == format!("Basic {}", BASE64_STANDARD.encode("username:password")) { HttpResponse::Ok() } else { HttpResponse::BadRequest() } }), ) }); // set authorization header to Basic <base64 encoded username:password> let request = srv.get("/").basic_auth("username", "password"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn client_bearer_auth() { let srv = actix_test::start(|| { App::new().route( "/", web::to(|req: HttpRequest| { if req .headers() .get(header::AUTHORIZATION) .unwrap() .to_str() .unwrap() == "Bearer someS3cr3tAutht0k3n" { HttpResponse::Ok() } else { HttpResponse::BadRequest() } }), ) }); // set authorization header to Bearer <token> let request = srv.get("/").bearer_auth("someS3cr3tAutht0k3n"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn local_address() { let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let srv = actix_test::start(move || { App::new().service( web::resource("/").route(web::to(move |req: HttpRequest| async move { assert_eq!(req.peer_addr().unwrap().ip(), ip); Ok::<_, Error>(HttpResponse::Ok()) })), ) }); let client = awc::Client::builder().local_address(ip).finish(); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status(), 200); let client = awc::Client::builder() .connector( // connector local address setting should always be override by client builder. awc::Connector::new().local_address(IpAddr::V4(Ipv4Addr::new(128, 0, 0, 1))), ) .local_address(ip) .finish(); let res = client.get(srv.url("/")).send().await.unwrap(); assert_eq!(res.status(), 200); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/tests/test_ws.rs
awc/tests/test_ws.rs
use std::io; use actix_codec::Framed; use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response}; use actix_http_test::test_server; use actix_utils::future::ok; use bytes::Bytes; use futures_util::{SinkExt as _, StreamExt as _}; async fn ws_service(req: ws::Frame) -> Result<ws::Message, io::Error> { match req { ws::Frame::Ping(msg) => Ok(ws::Message::Pong(msg)), ws::Frame::Text(text) => Ok(ws::Message::Text( String::from_utf8(Vec::from(text.as_ref())).unwrap().into(), )), ws::Frame::Binary(bin) => Ok(ws::Message::Binary(bin)), ws::Frame::Close(reason) => Ok(ws::Message::Close(reason)), _ => Ok(ws::Message::Close(None)), } } #[actix_rt::test] async fn test_simple() { let mut srv = test_server(|| { HttpService::build() .upgrade(|(req, mut framed): (Request, Framed<_, _>)| { async move { let res = ws::handshake_response(req.head()).finish(); // send handshake response framed .send(h1::Message::Item((res.drop_body(), BodySize::None))) .await?; // start WebSocket service let framed = framed.replace_codec(ws::Codec::new()); ws::Dispatcher::with(framed, ws_service).await } }) .finish(|_| ok::<_, Error>(Response::not_found())) .tcp() }) .await; // client service let mut framed = srv.ws().await.unwrap(); framed.send(ws::Message::Text("text".into())).await.unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text"))); framed .send(ws::Message::Binary("text".into())) .await .unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, ws::Frame::Binary(Bytes::from_static(b"text"))); framed.send(ws::Message::Ping("text".into())).await.unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, ws::Frame::Pong("text".to_string().into())); framed .send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))) .await .unwrap(); let item = framed.next().await.unwrap().unwrap(); assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into()))); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/tests/test_connector.rs
awc/tests/test_connector.rs
#![cfg(feature = "openssl")] extern crate tls_openssl as openssl; use actix_http::HttpService; use actix_http_test::test_server; use actix_service::{map_config, ServiceFactoryExt}; use actix_web::{dev::AppConfig, http::Version, web, App, HttpResponse}; use openssl::{ pkey::PKey, ssl::{SslAcceptor, SslConnector, SslMethod, SslVerifyMode}, x509::X509, }; fn tls_config() -> SslAcceptor { let rcgen::CertifiedKey { cert, key_pair } = rcgen::generate_simple_self_signed(["localhost".to_owned()]).unwrap(); let cert_file = cert.pem(); let key_file = key_pair.serialize_pem(); let cert = X509::from_pem(cert_file.as_bytes()).unwrap(); let key = PKey::private_key_from_pem(key_file.as_bytes()).unwrap(); let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap(); builder.set_certificate(&cert).unwrap(); builder.set_private_key(&key).unwrap(); builder.set_alpn_select_callback(|_, protos| { const H2: &[u8] = b"\x02h2"; if protos.windows(3).any(|window| window == H2) { Ok(b"h2") } else { Err(openssl::ssl::AlpnError::NOACK) } }); builder.set_alpn_protos(b"\x02h2").unwrap(); builder.build() } #[actix_rt::test] async fn test_connection_window_size() { let srv = test_server(|| { HttpService::build() .h2(map_config( App::new().service(web::resource("/").route(web::to(HttpResponse::Ok))), |_| AppConfig::default(), )) .openssl(tls_config()) .map_err(|_| ()) }) .await; // disable ssl verification let mut builder = SslConnector::builder(SslMethod::tls()).unwrap(); builder.set_verify(SslVerifyMode::NONE); let _ = builder .set_alpn_protos(b"\x02h2\x08http/1.1") .map_err(|e| log::error!("Can not set alpn protocol: {:?}", e)); let client = awc::Client::builder() .connector(awc::Connector::new().openssl(builder.build())) .initial_window_size(100) .initial_connection_window_size(100) .finish(); let request = client.get(srv.surl("/")).send(); let response = request.await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.version(), Version::HTTP_2); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/tests/utils.rs
awc/tests/utils.rs
// compiling some tests will trigger unused function warnings even though other tests use them #![allow(dead_code)] use std::io::{Read as _, Write as _}; pub mod gzip { use flate2::{read::GzDecoder, write::GzEncoder, Compression}; use super::*; pub fn encode(bytes: impl AsRef<[u8]>) -> Vec<u8> { let mut encoder = GzEncoder::new(Vec::new(), Compression::fast()); encoder.write_all(bytes.as_ref()).unwrap(); encoder.finish().unwrap() } pub fn decode(bytes: impl AsRef<[u8]>) -> Vec<u8> { let mut decoder = GzDecoder::new(bytes.as_ref()); let mut buf = Vec::new(); decoder.read_to_end(&mut buf).unwrap(); buf } } pub mod deflate { use flate2::{read::ZlibDecoder, write::ZlibEncoder, Compression}; use super::*; pub fn encode(bytes: impl AsRef<[u8]>) -> Vec<u8> { let mut encoder = ZlibEncoder::new(Vec::new(), Compression::fast()); encoder.write_all(bytes.as_ref()).unwrap(); encoder.finish().unwrap() } pub fn decode(bytes: impl AsRef<[u8]>) -> Vec<u8> { let mut decoder = ZlibDecoder::new(bytes.as_ref()); let mut buf = Vec::new(); decoder.read_to_end(&mut buf).unwrap(); buf } } pub mod brotli { use ::brotli::{reader::Decompressor as BrotliDecoder, CompressorWriter as BrotliEncoder}; use super::*; pub fn encode(bytes: impl AsRef<[u8]>) -> Vec<u8> { let mut encoder = BrotliEncoder::new( Vec::new(), 8 * 1024, // 32 KiB buffer 3, // BROTLI_PARAM_QUALITY 22, // BROTLI_PARAM_LGWIN ); encoder.write_all(bytes.as_ref()).unwrap(); encoder.flush().unwrap(); encoder.into_inner() } pub fn decode(bytes: impl AsRef<[u8]>) -> Vec<u8> { let mut decoder = BrotliDecoder::new(bytes.as_ref(), 8_096); let mut buf = Vec::new(); decoder.read_to_end(&mut buf).unwrap(); buf } } pub mod zstd { use ::zstd::stream::{read::Decoder, write::Encoder}; use super::*; pub fn encode(bytes: impl AsRef<[u8]>) -> Vec<u8> { let mut encoder = Encoder::new(Vec::new(), 3).unwrap(); encoder.write_all(bytes.as_ref()).unwrap(); encoder.finish().unwrap() } pub fn decode(bytes: impl AsRef<[u8]>) -> Vec<u8> { let mut decoder = Decoder::new(bytes.as_ref()).unwrap(); let mut buf = Vec::new(); decoder.read_to_end(&mut buf).unwrap(); buf } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/awc/examples/client.rs
awc/examples/client.rs
//! Demonstrates construction and usage of a TLS-capable HTTP client. extern crate tls_rustls_0_23 as rustls; use std::{error::Error as StdError, sync::Arc}; use actix_tls::connect::rustls_0_23::webpki_roots_cert_store; use rustls::ClientConfig; #[actix_rt::main] async fn main() -> Result<(), Box<dyn StdError>> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); let mut config = ClientConfig::builder() .with_root_certificates(webpki_roots_cert_store()) .with_no_client_auth(); let protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; config.alpn_protocols = protos; // construct request builder with TLS support let client = awc::Client::builder() .connector(awc::Connector::new().rustls_0_23(Arc::new(config))) .finish(); // configure request let request = client .get("https://www.rust-lang.org/") .append_header(("User-Agent", "awc/3.0")); println!("Request: {request:?}"); let mut response = request.send().await?; // server response head println!("Response: {response:?}"); // read response body let body = response.body().await?; println!("Downloaded: {:?} bytes", body.len()); Ok(()) }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/resource.rs
actix-router/src/resource.rs
use std::{ borrow::{Borrow, Cow}, collections::HashMap, hash::{BuildHasher, Hash, Hasher}, mem, }; use tracing::error; use crate::{ path::PathItem, regex_set::{escape, Regex, RegexSet}, IntoPatterns, Patterns, Resource, ResourcePath, }; const MAX_DYNAMIC_SEGMENTS: usize = 16; /// Regex flags to allow '.' in regex to match '\n' /// /// See the docs under: https://docs.rs/regex/1/regex/#grouping-and-flags const REGEX_FLAGS: &str = "(?s-m)"; /// Describes the set of paths that match to a resource. /// /// `ResourceDef`s are effectively a way to transform the a custom resource pattern syntax into /// suitable regular expressions from which to check matches with paths and capture portions of a /// matched path into variables. Common cases are on a fast path that avoids going through the /// regex engine. /// /// /// # Pattern Format and Matching Behavior /// Resource pattern is defined as a string of zero or more _segments_ where each segment is /// preceded by a slash `/`. /// /// This means that pattern string __must__ either be empty or begin with a slash (`/`). This also /// implies that a trailing slash in pattern defines an empty segment. For example, the pattern /// `"/user/"` has two segments: `["user", ""]` /// /// A key point to understand is that `ResourceDef` matches segments, not strings. Segments are /// matched individually. For example, the pattern `/user/` is not considered a prefix for the path /// `/user/123/456`, because the second segment doesn't match: `["user", ""]` /// vs `["user", "123", "456"]`. /// /// This definition is consistent with the definition of absolute URL path in /// [RFC 3986 §3.3](https://datatracker.ietf.org/doc/html/rfc3986#section-3.3) /// /// /// # Static Resources /// A static resource is the most basic type of definition. Pass a pattern to [new][Self::new]. /// Conforming paths must match the pattern exactly. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// let resource = ResourceDef::new("/home"); /// /// assert!(resource.is_match("/home")); /// /// assert!(!resource.is_match("/home/")); /// assert!(!resource.is_match("/home/new")); /// assert!(!resource.is_match("/homes")); /// assert!(!resource.is_match("/search")); /// ``` /// /// # Dynamic Segments /// Also known as "path parameters". Resources can define sections of a pattern that be extracted /// from a conforming path, if it conforms to (one of) the resource pattern(s). /// /// The marker for a dynamic segment is curly braces wrapping an identifier. For example, /// `/user/{id}` would match paths like `/user/123` or `/user/james` and be able to extract the user /// IDs "123" and "james", respectively. /// /// However, this resource pattern (`/user/{id}`) would, not cover `/user/123/stars` (unless /// constructed as a prefix; see next section) since the default pattern for segments matches all /// characters until it finds a `/` character (or the end of the path). Custom segment patterns are /// covered further down. /// /// Dynamic segments do not need to be delimited by `/` characters, they can be defined within a /// path segment. For example, `/rust-is-{opinion}` can match the paths `/rust-is-cool` and /// `/rust-is-hard`. /// /// For information on capturing segment values from paths or other custom resource types, /// see [`capture_match_info`][Self::capture_match_info] /// and [`capture_match_info_fn`][Self::capture_match_info_fn]. /// /// A resource definition can contain at most 16 dynamic segments. /// /// ## Examples /// ``` /// use actix_router::{Path, ResourceDef}; /// /// let resource = ResourceDef::prefix("/user/{id}"); /// /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("/user")); /// assert!(!resource.is_match("/user/")); /// /// let mut path = Path::new("/user/123"); /// resource.capture_match_info(&mut path); /// assert_eq!(path.get("id").unwrap(), "123"); /// ``` /// /// # Prefix Resources /// A prefix resource is defined as pattern that can match just the start of a path, up to a /// segment boundary. /// /// Prefix patterns with a trailing slash may have an unexpected, though correct, behavior. /// They define and therefore require an empty segment in order to match. It is easier to understand /// this behavior after reading the [matching behavior section]. Examples are given below. /// /// The empty pattern (`""`), as a prefix, matches any path. /// /// Prefix resources can contain dynamic segments. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// let resource = ResourceDef::prefix("/home"); /// assert!(resource.is_match("/home")); /// assert!(resource.is_match("/home/new")); /// assert!(!resource.is_match("/homes")); /// /// // prefix pattern with a trailing slash /// let resource = ResourceDef::prefix("/user/{id}/"); /// assert!(resource.is_match("/user/123/")); /// assert!(resource.is_match("/user/123//stars")); /// assert!(!resource.is_match("/user/123/stars")); /// assert!(!resource.is_match("/user/123")); /// ``` /// /// # Custom Regex Segments /// Dynamic segments can be customised to only match a specific regular expression. It can be /// helpful to do this if resource definitions would otherwise conflict and cause one to /// be inaccessible. /// /// The regex used when capturing segment values can be specified explicitly using this syntax: /// `{name:regex}`. For example, `/user/{id:\d+}` will only match paths where the user ID /// is numeric. /// /// The regex could potentially match multiple segments. If this is not wanted, then care must be /// taken to avoid matching a slash `/`. It is guaranteed, however, that the match ends at a /// segment boundary; the pattern `r"(/|$)` is always appended to the regex. /// /// By default, dynamic segments use this regex: `[^/]+`. This shows why it is the case, as shown in /// the earlier section, that segments capture a slice of the path up to the next `/` character. /// /// Custom regex segments can be used in static and prefix resource definition variants. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// let resource = ResourceDef::new(r"/user/{id:\d+}"); /// assert!(resource.is_match("/user/123")); /// assert!(resource.is_match("/user/314159")); /// assert!(!resource.is_match("/user/abc")); /// ``` /// /// # Tail Segments /// As a shortcut to defining a custom regex for matching _all_ remaining characters (not just those /// up until a `/` character), there is a special pattern to match (and capture) the remaining /// path portion. /// /// To do this, use the segment pattern: `{name}*`. Since a tail segment also has a name, values are /// extracted in the same way as non-tail dynamic segments. /// /// ## Examples /// ``` /// # use actix_router::{Path, ResourceDef}; /// let resource = ResourceDef::new("/blob/{tail}*"); /// assert!(resource.is_match("/blob/HEAD/Cargo.toml")); /// assert!(resource.is_match("/blob/HEAD/README.md")); /// /// let mut path = Path::new("/blob/main/LICENSE"); /// resource.capture_match_info(&mut path); /// assert_eq!(path.get("tail").unwrap(), "main/LICENSE"); /// ``` /// /// # Multi-Pattern Resources /// For resources that can map to multiple distinct paths, it may be suitable to use /// multi-pattern resources by passing an array/vec to [`new`][Self::new]. They will be combined /// into a regex set which is usually quicker to check matches on than checking each /// pattern individually. /// /// Multi-pattern resources can contain dynamic segments just like single pattern ones. /// However, take care to use consistent and semantically-equivalent segment names; it could affect /// expectations in the router using these definitions and cause runtime panics. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// let resource = ResourceDef::new(["/home", "/index"]); /// assert!(resource.is_match("/home")); /// assert!(resource.is_match("/index")); /// ``` /// /// # Trailing Slashes /// It should be noted that this library takes no steps to normalize intra-path or trailing slashes. /// As such, all resource definitions implicitly expect a pre-processing step to normalize paths if /// you wish to accommodate "recoverable" path errors. Below are several examples of resource-path /// pairs that would not be compatible. /// /// ## Examples /// ``` /// # use actix_router::ResourceDef; /// assert!(!ResourceDef::new("/root").is_match("/root/")); /// assert!(!ResourceDef::new("/root/").is_match("/root")); /// assert!(!ResourceDef::prefix("/root/").is_match("/root")); /// ``` /// /// [matching behavior section]: #pattern-format-and-matching-behavior #[derive(Clone, Debug)] pub struct ResourceDef { id: u16, /// Optional name of resource. name: Option<String>, /// Pattern that generated the resource definition. patterns: Patterns, is_prefix: bool, /// Pattern type. pat_type: PatternType, /// List of segments that compose the pattern, in order. segments: Vec<PatternSegment>, } #[derive(Debug, Clone, PartialEq)] enum PatternSegment { /// Literal slice of pattern. Const(String), /// Name of dynamic segment. Var(String), } #[derive(Debug, Clone)] #[allow(clippy::large_enum_variant)] enum PatternType { /// Single constant/literal segment. Static(String), /// Single regular expression and list of dynamic segment names. Dynamic(Regex, Vec<&'static str>), /// Regular expression set and list of component expressions plus dynamic segment names. DynamicSet(RegexSet, Vec<(Regex, Vec<&'static str>)>), } impl ResourceDef { /// Constructs a new resource definition from patterns. /// /// Multi-pattern resources can be constructed by providing a slice (or vec) of patterns. /// /// # Panics /// Panics if any path patterns are malformed. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// let resource = ResourceDef::new("/user/{id}"); /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("/user/123/stars")); /// assert!(!resource.is_match("user/1234")); /// assert!(!resource.is_match("/foo")); /// /// let resource = ResourceDef::new(["/profile", "/user/{id}"]); /// assert!(resource.is_match("/profile")); /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("user/123")); /// assert!(!resource.is_match("/foo")); /// ``` pub fn new<T: IntoPatterns>(paths: T) -> Self { Self::construct(paths, false) } /// Constructs a new resource definition using a pattern that performs prefix matching. /// /// More specifically, the regular expressions generated for matching are different when using /// this method vs using `new`; they will not be appended with the `$` meta-character that /// matches the end of an input. /// /// Although it will compile and run correctly, it is meaningless to construct a prefix /// resource definition with a tail segment; use [`new`][Self::new] in this case. /// /// # Panics /// Panics if path pattern is malformed. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// let resource = ResourceDef::prefix("/user/{id}"); /// assert!(resource.is_match("/user/123")); /// assert!(resource.is_match("/user/123/stars")); /// assert!(!resource.is_match("user/123")); /// assert!(!resource.is_match("user/123/stars")); /// assert!(!resource.is_match("/foo")); /// ``` pub fn prefix<T: IntoPatterns>(paths: T) -> Self { ResourceDef::construct(paths, true) } /// Constructs a new resource definition using a string pattern that performs prefix matching, /// ensuring a leading `/` if pattern is not empty. /// /// # Panics /// Panics if path pattern is malformed. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// let resource = ResourceDef::root_prefix("user/{id}"); /// /// assert_eq!(&resource, &ResourceDef::prefix("/user/{id}")); /// assert_eq!(&resource, &ResourceDef::root_prefix("/user/{id}")); /// assert_ne!(&resource, &ResourceDef::new("user/{id}")); /// assert_ne!(&resource, &ResourceDef::new("/user/{id}")); /// /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("user/123")); /// ``` pub fn root_prefix(path: &str) -> Self { ResourceDef::prefix(insert_slash(path).into_owned()) } /// Returns a numeric resource ID. /// /// If not explicitly set using [`set_id`][Self::set_id], this will return `0`. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// assert_eq!(resource.id(), 0); /// /// resource.set_id(42); /// assert_eq!(resource.id(), 42); /// ``` pub fn id(&self) -> u16 { self.id } /// Set numeric resource ID. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// resource.set_id(42); /// assert_eq!(resource.id(), 42); /// ``` pub fn set_id(&mut self, id: u16) { self.id = id; } /// Returns resource definition name, if set. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// assert!(resource.name().is_none()); /// /// resource.set_name("root"); /// assert_eq!(resource.name().unwrap(), "root"); pub fn name(&self) -> Option<&str> { self.name.as_deref() } /// Assigns a new name to the resource. /// /// # Panics /// Panics if `name` is an empty string. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// resource.set_name("root"); /// assert_eq!(resource.name().unwrap(), "root"); /// ``` pub fn set_name(&mut self, name: impl Into<String>) { let name = name.into(); assert!(!name.is_empty(), "resource name should not be empty"); self.name = Some(name) } /// Returns `true` if pattern type is prefix. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// assert!(ResourceDef::prefix("/user").is_prefix()); /// assert!(!ResourceDef::new("/user").is_prefix()); /// ``` pub fn is_prefix(&self) -> bool { self.is_prefix } /// Returns the pattern string that generated the resource definition. /// /// If definition is constructed with multiple patterns, the first pattern is returned. To get /// all patterns, use [`patterns_iter`][Self::pattern_iter]. If resource has 0 patterns, /// returns `None`. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/user/{id}"); /// assert_eq!(resource.pattern().unwrap(), "/user/{id}"); /// /// let mut resource = ResourceDef::new(["/profile", "/user/{id}"]); /// assert_eq!(resource.pattern(), Some("/profile")); pub fn pattern(&self) -> Option<&str> { match &self.patterns { Patterns::Single(pattern) => Some(pattern.as_str()), Patterns::List(patterns) => patterns.first().map(AsRef::as_ref), } } /// Returns iterator of pattern strings that generated the resource definition. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut resource = ResourceDef::new("/root"); /// let mut iter = resource.pattern_iter(); /// assert_eq!(iter.next().unwrap(), "/root"); /// assert!(iter.next().is_none()); /// /// let mut resource = ResourceDef::new(["/root", "/backup"]); /// let mut iter = resource.pattern_iter(); /// assert_eq!(iter.next().unwrap(), "/root"); /// assert_eq!(iter.next().unwrap(), "/backup"); /// assert!(iter.next().is_none()); pub fn pattern_iter(&self) -> impl Iterator<Item = &str> { struct PatternIter<'a> { patterns: &'a Patterns, list_idx: usize, done: bool, } impl<'a> Iterator for PatternIter<'a> { type Item = &'a str; fn next(&mut self) -> Option<Self::Item> { match &self.patterns { Patterns::Single(pattern) => { if self.done { return None; } self.done = true; Some(pattern.as_str()) } Patterns::List(patterns) if patterns.is_empty() => None, Patterns::List(patterns) => match patterns.get(self.list_idx) { Some(pattern) => { self.list_idx += 1; Some(pattern.as_str()) } None => { // fast path future call self.done = true; None } }, } } fn size_hint(&self) -> (usize, Option<usize>) { match &self.patterns { Patterns::Single(_) => (1, Some(1)), Patterns::List(patterns) => (patterns.len(), Some(patterns.len())), } } } PatternIter { patterns: &self.patterns, list_idx: 0, done: false, } } /// Joins two resources. /// /// Resulting resource is prefix if `other` is prefix. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let joined = ResourceDef::prefix("/root").join(&ResourceDef::prefix("/seg")); /// assert_eq!(joined, ResourceDef::prefix("/root/seg")); /// ``` pub fn join(&self, other: &ResourceDef) -> ResourceDef { let patterns = self .pattern_iter() .flat_map(move |this| other.pattern_iter().map(move |other| (this, other))) .map(|(this, other)| { let mut pattern = String::with_capacity(this.len() + other.len()); pattern.push_str(this); pattern.push_str(other); pattern }) .collect::<Vec<_>>(); match patterns.len() { 1 => ResourceDef::construct(&patterns[0], other.is_prefix()), _ => ResourceDef::construct(patterns, other.is_prefix()), } } /// Returns `true` if `path` matches this resource. /// /// The behavior of this method depends on how the `ResourceDef` was constructed. For example, /// static resources will not be able to match as many paths as dynamic and prefix resources. /// See [`ResourceDef`] struct docs for details on resource definition types. /// /// This method will always agree with [`find_match`][Self::find_match] on whether the path /// matches or not. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// // static resource /// let resource = ResourceDef::new("/user"); /// assert!(resource.is_match("/user")); /// assert!(!resource.is_match("/users")); /// assert!(!resource.is_match("/user/123")); /// assert!(!resource.is_match("/foo")); /// /// // dynamic resource /// let resource = ResourceDef::new("/user/{user_id}"); /// assert!(resource.is_match("/user/123")); /// assert!(!resource.is_match("/user/123/stars")); /// /// // prefix resource /// let resource = ResourceDef::prefix("/root"); /// assert!(resource.is_match("/root")); /// assert!(resource.is_match("/root/leaf")); /// assert!(!resource.is_match("/roots")); /// /// // more examples are shown in the `ResourceDef` struct docs /// ``` #[inline] pub fn is_match(&self, path: &str) -> bool { // this function could be expressed as: // `self.find_match(path).is_some()` // but this skips some checks and uses potentially faster regex methods match &self.pat_type { PatternType::Static(pattern) => self.static_match(pattern, path).is_some(), PatternType::Dynamic(re, _) => re.is_match(path), PatternType::DynamicSet(re, _) => re.is_match(path), } } /// Tries to match `path` to this resource, returning the position in the path where the /// match ends. /// /// This method will always agree with [`is_match`][Self::is_match] on whether the path matches /// or not. /// /// # Examples /// ``` /// use actix_router::ResourceDef; /// /// // static resource /// let resource = ResourceDef::new("/user"); /// assert_eq!(resource.find_match("/user"), Some(5)); /// assert!(resource.find_match("/user/").is_none()); /// assert!(resource.find_match("/user/123").is_none()); /// assert!(resource.find_match("/foo").is_none()); /// /// // constant prefix resource /// let resource = ResourceDef::prefix("/user"); /// assert_eq!(resource.find_match("/user"), Some(5)); /// assert_eq!(resource.find_match("/user/"), Some(5)); /// assert_eq!(resource.find_match("/user/123"), Some(5)); /// /// // dynamic prefix resource /// let resource = ResourceDef::prefix("/user/{id}"); /// assert_eq!(resource.find_match("/user/123"), Some(9)); /// assert_eq!(resource.find_match("/user/1234/"), Some(10)); /// assert_eq!(resource.find_match("/user/12345/stars"), Some(11)); /// assert!(resource.find_match("/user/").is_none()); /// /// // multi-pattern resource /// let resource = ResourceDef::new(["/user/{id}", "/profile/{id}"]); /// assert_eq!(resource.find_match("/user/123"), Some(9)); /// assert_eq!(resource.find_match("/profile/1234"), Some(13)); /// ``` pub fn find_match(&self, path: &str) -> Option<usize> { match &self.pat_type { PatternType::Static(pattern) => self.static_match(pattern, path), PatternType::Dynamic(re, _) => Some(re.captures(path)?[1].len()), PatternType::DynamicSet(re, params) => { let idx = re.first_match_idx(path)?; let (ref pattern, _) = params[idx]; Some(pattern.captures(path)?[1].len()) } } } /// Collects dynamic segment values into `resource`. /// /// Returns `true` if `path` matches this resource. /// /// # Examples /// ``` /// use actix_router::{Path, ResourceDef}; /// /// let resource = ResourceDef::prefix("/user/{id}"); /// let mut path = Path::new("/user/123/stars"); /// assert!(resource.capture_match_info(&mut path)); /// assert_eq!(path.get("id").unwrap(), "123"); /// assert_eq!(path.unprocessed(), "/stars"); /// /// let resource = ResourceDef::new("/blob/{path}*"); /// let mut path = Path::new("/blob/HEAD/Cargo.toml"); /// assert!(resource.capture_match_info(&mut path)); /// assert_eq!(path.get("path").unwrap(), "HEAD/Cargo.toml"); /// assert_eq!(path.unprocessed(), ""); /// ``` pub fn capture_match_info<R: Resource>(&self, resource: &mut R) -> bool { self.capture_match_info_fn(resource, |_| true) } /// Collects dynamic segment values into `resource` after matching paths and executing /// check function. /// /// The check function is given a reference to the passed resource and optional arbitrary data. /// This is useful if you want to conditionally match on some non-path related aspect of the /// resource type. /// /// Returns `true` if resource path matches this resource definition _and_ satisfies the /// given check function. /// /// # Examples /// ``` /// use actix_router::{Path, ResourceDef}; /// /// fn try_match(resource: &ResourceDef, path: &mut Path<&str>) -> bool { /// let admin_allowed = std::env::var("ADMIN_ALLOWED").is_ok(); /// /// resource.capture_match_info_fn( /// path, /// // when env var is not set, reject when path contains "admin" /// |path| !(!admin_allowed && path.as_str().contains("admin")), /// ) /// } /// /// let resource = ResourceDef::prefix("/user/{id}"); /// /// // path matches; segment values are collected into path /// let mut path = Path::new("/user/james/stars"); /// assert!(try_match(&resource, &mut path)); /// assert_eq!(path.get("id").unwrap(), "james"); /// assert_eq!(path.unprocessed(), "/stars"); /// /// // path matches but fails check function; no segments are collected /// let mut path = Path::new("/user/admin/stars"); /// assert!(!try_match(&resource, &mut path)); /// assert_eq!(path.unprocessed(), "/user/admin/stars"); /// ``` pub fn capture_match_info_fn<R, F>(&self, resource: &mut R, check_fn: F) -> bool where R: Resource, F: FnOnce(&R) -> bool, { let mut segments = <[PathItem; MAX_DYNAMIC_SEGMENTS]>::default(); let path = resource.resource_path(); let path_str = path.unprocessed(); let (matched_len, matched_vars) = match &self.pat_type { PatternType::Static(pattern) => match self.static_match(pattern, path_str) { Some(len) => (len, None), None => return false, }, PatternType::Dynamic(re, names) => { let captures = match re.captures(path.unprocessed()) { Some(captures) => captures, _ => return false, }; for (no, name) in names.iter().enumerate() { if let Some(m) = captures.name(name) { segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16); } else { error!("Dynamic path match but not all segments found: {}", name); return false; } } (captures[1].len(), Some(names)) } PatternType::DynamicSet(re, params) => { let path = path.unprocessed(); let (pattern, names) = match re.first_match_idx(path) { Some(idx) => &params[idx], _ => return false, }; let captures = match pattern.captures(path.path()) { Some(captures) => captures, _ => return false, }; for (no, name) in names.iter().enumerate() { if let Some(m) = captures.name(name) { segments[no] = PathItem::Segment(m.start() as u16, m.end() as u16); } else { error!("Dynamic path match but not all segments found: {}", name); return false; } } (captures[1].len(), Some(names)) } }; if !check_fn(resource) { return false; } // Modify `path` to skip matched part and store matched segments let path = resource.resource_path(); if let Some(vars) = matched_vars { for i in 0..vars.len() { path.add(vars[i], mem::take(&mut segments[i])); } } path.skip(matched_len as u16); true } /// Assembles resource path using a closure that maps variable segment names to values. fn build_resource_path<F, I>(&self, path: &mut String, mut vars: F) -> bool where F: FnMut(&str) -> Option<I>, I: AsRef<str>, { for segment in &self.segments { match segment { PatternSegment::Const(val) => path.push_str(val), PatternSegment::Var(name) => match vars(name) { Some(val) => path.push_str(val.as_ref()), _ => return false, }, } } true } /// Assembles full resource path from iterator of dynamic segment values. /// /// Returns `true` on success. /// /// For multi-pattern resources, the first pattern is used under the assumption that it would be /// equivalent to any other choice. /// /// # Examples /// ``` /// # use actix_router::ResourceDef; /// let mut s = String::new(); /// let resource = ResourceDef::new("/user/{id}/post/{title}"); /// /// assert!(resource.resource_path_from_iter(&mut s, &["123", "my-post"])); /// assert_eq!(s, "/user/123/post/my-post"); /// ``` pub fn resource_path_from_iter<I>(&self, path: &mut String, values: I) -> bool where I: IntoIterator, I::Item: AsRef<str>, { let mut iter = values.into_iter(); self.build_resource_path(path, |_| iter.next()) } /// Assembles resource path from map of dynamic segment values. /// /// Returns `true` on success. /// /// For multi-pattern resources, the first pattern is used under the assumption that it would be /// equivalent to any other choice. /// /// # Examples /// ``` /// # use std::collections::HashMap; /// # use actix_router::ResourceDef; /// let mut s = String::new(); /// let resource = ResourceDef::new("/user/{id}/post/{title}"); /// /// let mut map = HashMap::new(); /// map.insert("id", "123"); /// map.insert("title", "my-post"); /// /// assert!(resource.resource_path_from_map(&mut s, &map)); /// assert_eq!(s, "/user/123/post/my-post"); /// ``` pub fn resource_path_from_map<K, V, S>( &self, path: &mut String, values: &HashMap<K, V, S>, ) -> bool where K: Borrow<str> + Eq + Hash, V: AsRef<str>, S: BuildHasher, { self.build_resource_path(path, |name| values.get(name)) } /// Returns true if `prefix` acts as a proper prefix (i.e., separated by a slash) in `path`. fn static_match(&self, pattern: &str, path: &str) -> Option<usize> { let rem = path.strip_prefix(pattern)?; match self.is_prefix { // resource is not a prefix so an exact match is needed false if rem.is_empty() => Some(pattern.len()), // resource is a prefix so rem should start with a path delimiter true if rem.is_empty() || rem.starts_with('/') => Some(pattern.len()), // otherwise, no match _ => None, } } fn construct<T: IntoPatterns>(paths: T, is_prefix: bool) -> Self { let patterns = paths.patterns(); let (pat_type, segments) = match &patterns { Patterns::Single(pattern) => ResourceDef::parse(pattern, is_prefix, false), // since zero length pattern sets are possible // just return a useless `ResourceDef` Patterns::List(patterns) if patterns.is_empty() => ( PatternType::DynamicSet(RegexSet::empty(), Vec::new()), Vec::new(), ), Patterns::List(patterns) => { let mut re_set = Vec::with_capacity(patterns.len()); let mut pattern_data = Vec::new(); let mut segments = None; for pattern in patterns { match ResourceDef::parse(pattern, is_prefix, true) { (PatternType::Dynamic(re, names), segs) => { re_set.push(re.as_str().to_owned()); pattern_data.push((re, names)); segments.get_or_insert(segs); } _ => unreachable!(), } } let pattern_re_set = RegexSet::new(re_set); let segments = segments.unwrap_or_default(); ( PatternType::DynamicSet(pattern_re_set, pattern_data), segments, ) } }; ResourceDef { id: 0, name: None, patterns, is_prefix, pat_type, segments, } } /// Parses a dynamic segment definition from a pattern. /// /// The returned tuple includes: /// - the segment descriptor, either `Var` or `Tail` /// - the segment's regex to check values against
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
true
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/path.rs
actix-router/src/path.rs
use std::{ borrow::Cow, ops::{DerefMut, Index}, }; use serde::{de, Deserialize}; use crate::{de::PathDeserializer, Resource, ResourcePath}; #[derive(Debug, Clone)] pub(crate) enum PathItem { Static(Cow<'static, str>), Segment(u16, u16), } impl Default for PathItem { fn default() -> Self { Self::Static(Cow::Borrowed("")) } } /// Resource path match information. /// /// If resource path contains variable patterns, `Path` stores them. #[derive(Debug, Clone, Default)] pub struct Path<T> { /// Full path representation. path: T, /// Number of characters in `path` that have been processed into `segments`. pub(crate) skip: u16, /// List of processed dynamic segments; name->value pairs. pub(crate) segments: Vec<(Cow<'static, str>, PathItem)>, } impl<T: ResourcePath> Path<T> { pub fn new(path: T) -> Path<T> { Path { path, skip: 0, segments: Vec::new(), } } /// Returns reference to inner path instance. #[inline] pub fn get_ref(&self) -> &T { &self.path } /// Returns mutable reference to inner path instance. #[inline] pub fn get_mut(&mut self) -> &mut T { &mut self.path } /// Returns full path as a string. #[inline] pub fn as_str(&self) -> &str { self.path.path() } /// Returns unprocessed part of the path. /// /// Returns empty string if no more is to be processed. #[inline] pub fn unprocessed(&self) -> &str { // clamp skip to path length let skip = (self.skip as usize).min(self.as_str().len()); &self.path.path()[skip..] } /// Returns unprocessed part of the path. #[doc(hidden)] #[deprecated(since = "0.6.0", note = "Use `.as_str()` or `.unprocessed()`.")] #[inline] pub fn path(&self) -> &str { let skip = self.skip as usize; let path = self.path.path(); if skip <= path.len() { &path[skip..] } else { "" } } /// Set new path. #[inline] pub fn set(&mut self, path: T) { self.path = path; self.skip = 0; self.segments.clear(); } /// Reset state. #[inline] pub fn reset(&mut self) { self.skip = 0; self.segments.clear(); } /// Skip first `n` chars in path. #[inline] pub fn skip(&mut self, n: u16) { self.skip += n; } pub(crate) fn add(&mut self, name: impl Into<Cow<'static, str>>, value: PathItem) { match value { PathItem::Static(seg) => self.segments.push((name.into(), PathItem::Static(seg))), PathItem::Segment(begin, end) => self.segments.push(( name.into(), PathItem::Segment(self.skip + begin, self.skip + end), )), } } #[doc(hidden)] pub fn add_static( &mut self, name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>, ) { self.segments .push((name.into(), PathItem::Static(value.into()))); } /// Check if there are any matched patterns. #[inline] pub fn is_empty(&self) -> bool { self.segments.is_empty() } /// Returns number of interpolated segments. #[inline] pub fn segment_count(&self) -> usize { self.segments.len() } /// Get matched parameter by name without type conversion pub fn get(&self, name: &str) -> Option<&str> { for (seg_name, val) in self.segments.iter() { if name == seg_name { return match val { PathItem::Static(ref seg) => Some(seg), PathItem::Segment(start, end) => { Some(&self.path.path()[(*start as usize)..(*end as usize)]) } }; } } None } /// Returns matched parameter by name. /// /// If keyed parameter is not available empty string is used as default value. pub fn query(&self, key: &str) -> &str { self.get(key).unwrap_or_default() } /// Return iterator to items in parameter container. pub fn iter(&self) -> PathIter<'_, T> { PathIter { idx: 0, params: self, } } /// Deserializes matching parameters to a specified type `U`. /// /// # Errors /// /// Returns error when dynamic path segments cannot be deserialized into a `U` type. pub fn load<'de, U: Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> { Deserialize::deserialize(PathDeserializer::new(self)) } } #[derive(Debug)] pub struct PathIter<'a, T> { idx: usize, params: &'a Path<T>, } impl<'a, T: ResourcePath> Iterator for PathIter<'a, T> { type Item = (&'a str, &'a str); #[inline] fn next(&mut self) -> Option<(&'a str, &'a str)> { if self.idx < self.params.segment_count() { let idx = self.idx; let res = match self.params.segments[idx].1 { PathItem::Static(ref seg) => seg, PathItem::Segment(start, end) => { &self.params.path.path()[(start as usize)..(end as usize)] } }; self.idx += 1; return Some((&self.params.segments[idx].0, res)); } None } } impl<'a, T: ResourcePath> Index<&'a str> for Path<T> { type Output = str; fn index(&self, name: &'a str) -> &str { self.get(name) .expect("Value for parameter is not available") } } impl<T: ResourcePath> Index<usize> for Path<T> { type Output = str; fn index(&self, idx: usize) -> &str { match self.segments[idx].1 { PathItem::Static(ref seg) => seg, PathItem::Segment(start, end) => &self.path.path()[(start as usize)..(end as usize)], } } } impl<T: ResourcePath> Resource for Path<T> { type Path = T; fn resource_path(&mut self) -> &mut Path<Self::Path> { self } } impl<T, P> Resource for T where T: DerefMut<Target = Path<P>>, P: ResourcePath, { type Path = P; fn resource_path(&mut self) -> &mut Path<Self::Path> { &mut *self } } #[cfg(test)] mod tests { use std::cell::RefCell; use super::*; #[allow(clippy::needless_borrow)] #[test] fn deref_impls() { let mut foo = Path::new("/foo"); let _ = (&mut foo).resource_path(); let foo = RefCell::new(foo); let _ = foo.borrow_mut().resource_path(); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/router.rs
actix-router/src/router.rs
use crate::{IntoPatterns, Resource, ResourceDef}; #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct ResourceId(pub u16); /// Resource router. /// /// It matches a [routing resource](Resource) to an ordered list of _routes_. Each is defined by a /// single [`ResourceDef`] and contains two types of custom data: /// 1. The route _value_, of the generic type `T`. /// 1. Some _context_ data, of the generic type `U`, which is only provided to the check function in /// [`recognize_fn`](Self::recognize_fn). This parameter defaults to `()` and can be omitted if /// not required. pub struct Router<T, U = ()> { routes: Vec<(ResourceDef, T, U)>, } impl<T, U> Router<T, U> { /// Constructs new `RouterBuilder` with empty route list. pub fn build() -> RouterBuilder<T, U> { RouterBuilder { routes: Vec::new() } } /// Finds the value in the router that matches a given [routing resource](Resource). /// /// The match result, including the captured dynamic segments, in the `resource`. pub fn recognize<R>(&self, resource: &mut R) -> Option<(&T, ResourceId)> where R: Resource, { self.recognize_fn(resource, |_, _| true) } /// Same as [`recognize`](Self::recognize) but returns a mutable reference to the matched value. pub fn recognize_mut<R>(&mut self, resource: &mut R) -> Option<(&mut T, ResourceId)> where R: Resource, { self.recognize_mut_fn(resource, |_, _| true) } /// Finds the value in the router that matches a given [routing resource](Resource) and passes /// an additional predicate check using context data. /// /// Similar to [`recognize`](Self::recognize). However, before accepting the route as matched, /// the `check` closure is executed, passing the resource and each route's context data. If the /// closure returns true then the match result is stored into `resource` and a reference to /// the matched _value_ is returned. pub fn recognize_fn<R, F>(&self, resource: &mut R, mut check: F) -> Option<(&T, ResourceId)> where R: Resource, F: FnMut(&R, &U) -> bool, { for (rdef, val, ctx) in self.routes.iter() { if rdef.capture_match_info_fn(resource, |res| check(res, ctx)) { return Some((val, ResourceId(rdef.id()))); } } None } /// Same as [`recognize_fn`](Self::recognize_fn) but returns a mutable reference to the matched /// value. pub fn recognize_mut_fn<R, F>( &mut self, resource: &mut R, mut check: F, ) -> Option<(&mut T, ResourceId)> where R: Resource, F: FnMut(&R, &U) -> bool, { for (rdef, val, ctx) in self.routes.iter_mut() { if rdef.capture_match_info_fn(resource, |res| check(res, ctx)) { return Some((val, ResourceId(rdef.id()))); } } None } } /// Builder for an ordered [routing](Router) list. pub struct RouterBuilder<T, U = ()> { routes: Vec<(ResourceDef, T, U)>, } impl<T, U> RouterBuilder<T, U> { /// Adds a new route to the end of the routing list. /// /// Returns mutable references to elements of the new route. pub fn push( &mut self, rdef: ResourceDef, val: T, ctx: U, ) -> (&mut ResourceDef, &mut T, &mut U) { self.routes.push((rdef, val, ctx)); #[allow(clippy::map_identity)] // map is used to distribute &mut-ness to tuple elements self.routes .last_mut() .map(|(rdef, val, ctx)| (rdef, val, ctx)) .unwrap() } /// Finish configuration and create router instance. pub fn finish(self) -> Router<T, U> { Router { routes: self.routes, } } } /// Convenience methods provided when context data impls [`Default`] impl<T, U> RouterBuilder<T, U> where U: Default, { /// Registers resource for specified path. pub fn path(&mut self, path: impl IntoPatterns, val: T) -> (&mut ResourceDef, &mut T, &mut U) { self.push(ResourceDef::new(path), val, U::default()) } /// Registers resource for specified path prefix. pub fn prefix( &mut self, prefix: impl IntoPatterns, val: T, ) -> (&mut ResourceDef, &mut T, &mut U) { self.push(ResourceDef::prefix(prefix), val, U::default()) } /// Registers resource for [`ResourceDef`]. pub fn rdef(&mut self, rdef: ResourceDef, val: T) -> (&mut ResourceDef, &mut T, &mut U) { self.push(rdef, val, U::default()) } } #[cfg(test)] mod tests { use crate::{ path::Path, router::{ResourceId, Router}, }; #[allow(clippy::cognitive_complexity)] #[allow(clippy::literal_string_with_formatting_args)] #[test] fn test_recognizer_1() { let mut router = Router::<usize>::build(); router.path("/name", 10).0.set_id(0); router.path("/name/{val}", 11).0.set_id(1); router.path("/name/{val}/index.html", 12).0.set_id(2); router.path("/file/{file}.{ext}", 13).0.set_id(3); router.path("/v{val}/{val2}/index.html", 14).0.set_id(4); router.path("/v/{tail:.*}", 15).0.set_id(5); router.path("/test2/{test}.html", 16).0.set_id(6); router.path("/{test}/index.html", 17).0.set_id(7); let mut router = router.finish(); let mut path = Path::new("/unknown"); assert!(router.recognize_mut(&mut path).is_none()); let mut path = Path::new("/name"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 10); assert_eq!(info, ResourceId(0)); assert!(path.is_empty()); let mut path = Path::new("/name/value"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 11); assert_eq!(info, ResourceId(1)); assert_eq!(path.get("val").unwrap(), "value"); assert_eq!(&path["val"], "value"); let mut path = Path::new("/name/value2/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 12); assert_eq!(info, ResourceId(2)); assert_eq!(path.get("val").unwrap(), "value2"); let mut path = Path::new("/file/file.gz"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 13); assert_eq!(info, ResourceId(3)); assert_eq!(path.get("file").unwrap(), "file"); assert_eq!(path.get("ext").unwrap(), "gz"); let mut path = Path::new("/v2/ttt/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 14); assert_eq!(info, ResourceId(4)); assert_eq!(path.get("val").unwrap(), "2"); assert_eq!(path.get("val2").unwrap(), "ttt"); let mut path = Path::new("/v/blah-blah/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 15); assert_eq!(info, ResourceId(5)); assert_eq!(path.get("tail").unwrap(), "blah-blah/index.html"); let mut path = Path::new("/test2/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 16); assert_eq!(info, ResourceId(6)); assert_eq!(path.get("test").unwrap(), "index"); let mut path = Path::new("/bbb/index.html"); let (h, info) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 17); assert_eq!(info, ResourceId(7)); assert_eq!(path.get("test").unwrap(), "bbb"); } #[test] fn test_recognizer_2() { let mut router = Router::<usize>::build(); router.path("/index.json", 10); router.path("/{source}.json", 11); let mut router = router.finish(); let mut path = Path::new("/index.json"); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 10); let mut path = Path::new("/test.json"); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 11); } #[test] fn test_recognizer_with_prefix() { let mut router = Router::<usize>::build(); router.path("/name", 10).0.set_id(0); router.path("/name/{val}", 11).0.set_id(1); let mut router = router.finish(); let mut path = Path::new("/name"); path.skip(5); assert!(router.recognize_mut(&mut path).is_none()); let mut path = Path::new("/test/name"); path.skip(5); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 10); let mut path = Path::new("/test/name/value"); path.skip(5); let (h, id) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 11); assert_eq!(id, ResourceId(1)); assert_eq!(path.get("val").unwrap(), "value"); assert_eq!(&path["val"], "value"); // same patterns let mut router = Router::<usize>::build(); router.path("/name", 10); router.path("/name/{val}", 11); let mut router = router.finish(); // test skip beyond path length let mut path = Path::new("/name"); path.skip(6); assert!(router.recognize_mut(&mut path).is_none()); let mut path = Path::new("/test2/name"); path.skip(6); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 10); let mut path = Path::new("/test2/name-test"); path.skip(6); assert!(router.recognize_mut(&mut path).is_none()); let mut path = Path::new("/test2/name/ttt"); path.skip(6); let (h, _) = router.recognize_mut(&mut path).unwrap(); assert_eq!(*h, 11); assert_eq!(&path["val"], "ttt"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/lib.rs
actix-router/src/lib.rs
//! Resource path matching and router. #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_cfg))] mod de; mod path; mod pattern; mod quoter; mod regex_set; mod resource; mod resource_path; mod router; #[cfg(feature = "http")] mod url; #[cfg(feature = "http")] pub use self::url::Url; pub use self::{ de::PathDeserializer, path::Path, pattern::{IntoPatterns, Patterns}, quoter::Quoter, resource::ResourceDef, resource_path::{Resource, ResourcePath}, router::{ResourceId, Router, RouterBuilder}, };
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/pattern.rs
actix-router/src/pattern.rs
/// One or many patterns. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Patterns { Single(String), List(Vec<String>), } impl Patterns { pub fn is_empty(&self) -> bool { match self { Patterns::Single(_) => false, Patterns::List(pats) => pats.is_empty(), } } } /// Helper trait for type that could be converted to one or more path patterns. pub trait IntoPatterns { fn patterns(&self) -> Patterns; } impl IntoPatterns for String { fn patterns(&self) -> Patterns { Patterns::Single(self.clone()) } } impl IntoPatterns for &String { fn patterns(&self) -> Patterns { (*self).patterns() } } impl IntoPatterns for str { fn patterns(&self) -> Patterns { Patterns::Single(self.to_owned()) } } impl IntoPatterns for &str { fn patterns(&self) -> Patterns { (*self).patterns() } } impl IntoPatterns for bytestring::ByteString { fn patterns(&self) -> Patterns { Patterns::Single(self.to_string()) } } impl IntoPatterns for Patterns { fn patterns(&self) -> Patterns { self.clone() } } impl<T: AsRef<str>> IntoPatterns for Vec<T> { fn patterns(&self) -> Patterns { let mut patterns = self.iter().map(|v| v.as_ref().to_owned()); match patterns.size_hint() { (1, _) => Patterns::Single(patterns.next().unwrap()), _ => Patterns::List(patterns.collect()), } } } macro_rules! array_patterns_single (($tp:ty) => { impl IntoPatterns for [$tp; 1] { fn patterns(&self) -> Patterns { Patterns::Single(self[0].to_owned()) } } }); macro_rules! array_patterns_multiple (($tp:ty, $str_fn:expr, $($num:tt) +) => { // for each array length specified in space-separated $num $( impl IntoPatterns for [$tp; $num] { fn patterns(&self) -> Patterns { Patterns::List(self.iter().map($str_fn).collect()) } } )+ }); array_patterns_single!(&str); array_patterns_multiple!(&str, |&v| v.to_owned(), 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16); array_patterns_single!(String); array_patterns_multiple!(String, |v| v.clone(), 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16);
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/resource_path.rs
actix-router/src/resource_path.rs
use crate::Path; // TODO: this trait is necessary, document it // see impl Resource for ServiceRequest pub trait Resource { /// Type of resource's path returned in `resource_path`. type Path: ResourcePath; fn resource_path(&mut self) -> &mut Path<Self::Path>; } pub trait ResourcePath { fn path(&self) -> &str; } impl ResourcePath for String { fn path(&self) -> &str { self.as_str() } } impl ResourcePath for &str { fn path(&self) -> &str { self } } impl ResourcePath for bytestring::ByteString { fn path(&self) -> &str { self } } #[cfg(feature = "http")] impl ResourcePath for http::Uri { fn path(&self) -> &str { self.path() } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/url.rs
actix-router/src/url.rs
use crate::{Quoter, ResourcePath}; thread_local! { static DEFAULT_QUOTER: Quoter = Quoter::new(b"", b"%/+"); } #[derive(Debug, Clone, Default)] pub struct Url { uri: http::Uri, path: Option<String>, } impl Url { #[inline] pub fn new(uri: http::Uri) -> Url { let path = DEFAULT_QUOTER.with(|q| q.requote_str_lossy(uri.path())); Url { uri, path } } #[inline] pub fn new_with_quoter(uri: http::Uri, quoter: &Quoter) -> Url { Url { path: quoter.requote_str_lossy(uri.path()), uri, } } /// Returns URI. #[inline] pub fn uri(&self) -> &http::Uri { &self.uri } /// Returns path. #[inline] pub fn path(&self) -> &str { match self.path { Some(ref path) => path, _ => self.uri.path(), } } #[inline] pub fn update(&mut self, uri: &http::Uri) { self.uri = uri.clone(); self.path = DEFAULT_QUOTER.with(|q| q.requote_str_lossy(uri.path())); } #[inline] pub fn update_with_quoter(&mut self, uri: &http::Uri, quoter: &Quoter) { self.uri = uri.clone(); self.path = quoter.requote_str_lossy(uri.path()); } } impl ResourcePath for Url { #[inline] fn path(&self) -> &str { self.path() } } #[cfg(test)] mod tests { use std::fmt::Write as _; use http::Uri; use super::*; use crate::{Path, ResourceDef}; const PROTECTED: &[u8] = b"%/+"; fn match_url(pattern: &'static str, url: impl AsRef<str>) -> Path<Url> { let re = ResourceDef::new(pattern); let uri = Uri::try_from(url.as_ref()).unwrap(); let mut path = Path::new(Url::new(uri)); assert!(re.capture_match_info(&mut path)); path } fn percent_encode(data: &[u8]) -> String { data.iter() .fold(String::with_capacity(data.len() * 3), |mut buf, c| { write!(&mut buf, "%{:02X}", c).unwrap(); buf }) } #[test] fn parse_url() { let re = "/user/{id}/test"; let path = match_url(re, "/user/2345/test"); assert_eq!(path.get("id").unwrap(), "2345"); } #[test] fn protected_chars() { let re = "/user/{id}/test"; let encoded = percent_encode(PROTECTED); let path = match_url(re, format!("/user/{}/test", encoded)); // characters in captured segment remain unencoded assert_eq!(path.get("id").unwrap(), &encoded); // "%25" should never be decoded into '%' to guarantee the output is a valid // percent-encoded format let path = match_url(re, "/user/qwe%25/test"); assert_eq!(path.get("id").unwrap(), "qwe%25"); let path = match_url(re, "/user/qwe%25rty/test"); assert_eq!(path.get("id").unwrap(), "qwe%25rty"); } #[test] fn non_protected_ascii() { let non_protected_ascii = ('\u{0}'..='\u{7F}') .filter(|&c| c.is_ascii() && !PROTECTED.contains(&(c as u8))) .collect::<String>(); let encoded = percent_encode(non_protected_ascii.as_bytes()); let path = match_url("/user/{id}/test", format!("/user/{}/test", encoded)); assert_eq!(path.get("id").unwrap(), &non_protected_ascii); } #[test] fn valid_utf8_multi_byte() { let test = ('\u{FF00}'..='\u{FFFF}').collect::<String>(); let encoded = percent_encode(test.as_bytes()); let path = match_url("/a/{id}/b", format!("/a/{}/b", &encoded)); assert_eq!(path.get("id").unwrap(), &test); } #[test] fn invalid_utf8() { let invalid_utf8 = percent_encode((0x80..=0xff).collect::<Vec<_>>().as_slice()); let uri = Uri::try_from(format!("/{}", invalid_utf8)).unwrap(); let path = Path::new(Url::new(uri)); // We should always get a valid utf8 string assert!(String::from_utf8(path.as_str().as_bytes().to_owned()).is_ok()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/regex_set.rs
actix-router/src/regex_set.rs
//! Abstraction over `regex` and `regex-lite` depending on whether we have `unicode` crate feature //! enabled. use cfg_if::cfg_if; #[cfg(feature = "unicode")] pub(crate) use regex::{escape, Regex}; #[cfg(not(feature = "unicode"))] pub(crate) use regex_lite::{escape, Regex}; #[cfg(feature = "unicode")] #[derive(Debug, Clone)] pub(crate) struct RegexSet(regex::RegexSet); #[cfg(not(feature = "unicode"))] #[derive(Debug, Clone)] pub(crate) struct RegexSet(Vec<regex_lite::Regex>); impl RegexSet { /// Create a new regex set. /// /// # Panics /// /// Panics if any path patterns are malformed. pub(crate) fn new(re_set: Vec<String>) -> Self { cfg_if! { if #[cfg(feature = "unicode")] { Self(regex::RegexSet::new(re_set).unwrap()) } else { Self(re_set.iter().map(|re| Regex::new(re).unwrap()).collect()) } } } /// Create a new empty regex set. pub(crate) fn empty() -> Self { cfg_if! { if #[cfg(feature = "unicode")] { Self(regex::RegexSet::empty()) } else { Self(Vec::new()) } } } /// Returns true if regex set matches `path`. pub(crate) fn is_match(&self, path: &str) -> bool { cfg_if! { if #[cfg(feature = "unicode")] { self.0.is_match(path) } else { self.0.iter().any(|re| re.is_match(path)) } } } /// Returns index within `path` of first match. pub(crate) fn first_match_idx(&self, path: &str) -> Option<usize> { cfg_if! { if #[cfg(feature = "unicode")] { self.0.matches(path).into_iter().next() } else { Some(self.0.iter().enumerate().find(|(_, re)| re.is_match(path))?.0) } } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/quoter.rs
actix-router/src/quoter.rs
/// Partial percent-decoding. /// /// Performs percent-decoding on a slice but can selectively skip decoding certain sequences. /// /// # Examples /// ``` /// # use actix_router::Quoter; /// // + is set as a protected character and will not be decoded... /// let q = Quoter::new(&[], b"+"); /// /// // ...but the other encoded characters (like the hyphen below) will. /// assert_eq!(q.requote(b"/a%2Db%2Bc").unwrap(), b"/a-b%2Bc"); /// ``` pub struct Quoter { /// Simple bit-map of protected values in the 0-127 ASCII range. protected_table: AsciiBitmap, } impl Quoter { /// Constructs a new `Quoter` instance given a set of protected ASCII bytes. /// /// The first argument is ignored but is kept for backward compatibility. /// /// # Panics /// Panics if any of the `protected` bytes are not in the 0-127 ASCII range. pub fn new(_: &[u8], protected: &[u8]) -> Quoter { let mut protected_table = AsciiBitmap::default(); // prepare protected table for &ch in protected { protected_table.set_bit(ch); } Quoter { protected_table } } /// Decodes the next escape sequence, if any, and advances `val`. #[inline(always)] fn decode_next<'a>(&self, val: &mut &'a [u8]) -> Option<(&'a [u8], u8)> { for i in 0..val.len() { if let (prev, [b'%', p1, p2, rem @ ..]) = val.split_at(i) { if let Some(ch) = hex_pair_to_char(*p1, *p2) // ignore protected ascii bytes .filter(|&ch| !(ch < 128 && self.protected_table.bit_at(ch))) { *val = rem; return Some((prev, ch)); } } } None } /// Partially percent-decodes the given bytes. /// /// Escape sequences of the protected set are *not* decoded. /// /// Returns `None` when no modification to the original bytes was required. /// /// Invalid/incomplete percent-encoding sequences are passed unmodified. pub fn requote(&self, val: &[u8]) -> Option<Vec<u8>> { let mut remaining = val; // early return indicates that no percent-encoded sequences exist and we can skip allocation let (pre, decoded_char) = self.decode_next(&mut remaining)?; // decoded output will always be shorter than the input let mut decoded = Vec::<u8>::with_capacity(val.len()); // push first segment and decoded char decoded.extend_from_slice(pre); decoded.push(decoded_char); // decode and push rest of segments and decoded chars while let Some((prev, ch)) = self.decode_next(&mut remaining) { // this ugly conditional achieves +50% perf in cases where this is a tight loop. if !prev.is_empty() { decoded.extend_from_slice(prev); } decoded.push(ch); } decoded.extend_from_slice(remaining); Some(decoded) } pub(crate) fn requote_str_lossy(&self, val: &str) -> Option<String> { self.requote(val.as_bytes()) .map(|data| String::from_utf8_lossy(&data).into_owned()) } } /// Decode a ASCII hex-encoded pair to an integer. /// /// Returns `None` if either portion of the decoded pair does not evaluate to a valid hex value. /// /// - `0x33 ('3'), 0x30 ('0') => 0x30 ('0')` /// - `0x34 ('4'), 0x31 ('1') => 0x41 ('A')` /// - `0x36 ('6'), 0x31 ('1') => 0x61 ('a')` #[inline(always)] fn hex_pair_to_char(d1: u8, d2: u8) -> Option<u8> { let d_high = char::from(d1).to_digit(16)?; let d_low = char::from(d2).to_digit(16)?; // left shift high nibble by 4 bits Some(((d_high as u8) << 4) | (d_low as u8)) } #[derive(Debug, Default, Clone)] struct AsciiBitmap { array: [u8; 16], } impl AsciiBitmap { /// Sets bit in given bit-map to 1=true. /// /// # Panics /// Panics if `ch` index is out of bounds. fn set_bit(&mut self, ch: u8) { self.array[(ch >> 3) as usize] |= 0b1 << (ch & 0b111) } /// Returns true if bit to true in given bit-map. /// /// # Panics /// Panics if `ch` index is out of bounds. fn bit_at(&self, ch: u8) -> bool { self.array[(ch >> 3) as usize] & (0b1 << (ch & 0b111)) != 0 } } #[cfg(test)] mod tests { use super::*; #[test] fn custom_quoter() { let q = Quoter::new(b"", b"+"); assert_eq!(q.requote(b"/a%25c").unwrap(), b"/a%c"); assert_eq!(q.requote(b"/a%2Bc"), None); let q = Quoter::new(b"%+", b"/"); assert_eq!(q.requote(b"/a%25b%2Bc").unwrap(), b"/a%b+c"); assert_eq!(q.requote(b"/a%2fb"), None); assert_eq!(q.requote(b"/a%2Fb"), None); assert_eq!(q.requote(b"/a%0Ab").unwrap(), b"/a\nb"); assert_eq!(q.requote(b"/a%FE\xffb").unwrap(), b"/a\xfe\xffb"); assert_eq!(q.requote(b"/a\xfe\xffb"), None); } #[test] fn non_ascii() { let q = Quoter::new(b"%+", b"/"); assert_eq!(q.requote(b"/a%FE\xffb").unwrap(), b"/a\xfe\xffb"); assert_eq!(q.requote(b"/a\xfe\xffb"), None); } #[test] fn invalid_sequences() { let q = Quoter::new(b"%+", b"/"); assert_eq!(q.requote(b"/a%2x%2X%%"), None); assert_eq!(q.requote(b"/a%20%2X%%").unwrap(), b"/a %2X%%"); } #[test] fn quoter_no_modification() { let q = Quoter::new(b"", b""); assert_eq!(q.requote(b"/abc/../efg"), None); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/src/de.rs
actix-router/src/de.rs
use std::borrow::Cow; use serde::{ de::{self, Deserializer, Error as DeError, Visitor}, forward_to_deserialize_any, }; use crate::{ path::{Path, PathIter}, Quoter, ResourcePath, }; thread_local! { static FULL_QUOTER: Quoter = Quoter::new(b"", b""); } macro_rules! unsupported_type { ($trait_fn:ident, $name:expr) => { fn $trait_fn<V>(self, _: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::Error::custom(concat!("unsupported type: ", $name))) } }; } macro_rules! parse_single_value { ($trait_fn:ident) => { fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if self.path.segment_count() != 1 { Err(de::value::Error::custom( format!( "wrong number of parameters: {} expected 1", self.path.segment_count() ) .as_str(), )) } else { Value { value: &self.path[0], } .$trait_fn(visitor) } } }; } macro_rules! parse_value { ($trait_fn:ident, $visit_fn:ident, $tp:tt) => { fn $trait_fn<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { let decoded = FULL_QUOTER .with(|q| q.requote_str_lossy(self.value)) .map(Cow::Owned) .unwrap_or(Cow::Borrowed(self.value)); let v = decoded.parse().map_err(|_| { de::value::Error::custom(format!("can not parse {:?} to a {}", self.value, $tp)) })?; visitor.$visit_fn(v) } }; } pub struct PathDeserializer<'de, T: ResourcePath> { path: &'de Path<T>, } impl<'de, T: ResourcePath + 'de> PathDeserializer<'de, T> { pub fn new(path: &'de Path<T>) -> Self { PathDeserializer { path } } } impl<'de, T: ResourcePath + 'de> Deserializer<'de> for PathDeserializer<'de, T> { type Error = de::value::Error; fn deserialize_map<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_map(ParamsDeserializer { params: self.path.iter(), current: None, }) } fn deserialize_struct<V>( self, _: &'static str, _: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_map(visitor) } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit_struct<V>( self, _: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_unit(visitor) } fn deserialize_newtype_struct<V>( self, _: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_tuple<V>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if self.path.segment_count() < len { Err(de::value::Error::custom( format!( "wrong number of parameters: {} expected {}", self.path.segment_count(), len ) .as_str(), )) } else { visitor.visit_seq(ParamsSeq { params: self.path.iter(), }) } } fn deserialize_tuple_struct<V>( self, _: &'static str, len: usize, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if self.path.segment_count() < len { Err(de::value::Error::custom( format!( "wrong number of parameters: {} expected {}", self.path.segment_count(), len ) .as_str(), )) } else { visitor.visit_seq(ParamsSeq { params: self.path.iter(), }) } } fn deserialize_enum<V>( self, _: &'static str, _: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { if self.path.is_empty() { Err(de::value::Error::custom("expected at least one parameters")) } else { visitor.visit_enum(ValueEnum { value: &self.path[0], }) } } fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_seq(ParamsSeq { params: self.path.iter(), }) } unsupported_type!(deserialize_any, "'any'"); unsupported_type!(deserialize_option, "Option<T>"); unsupported_type!(deserialize_identifier, "identifier"); unsupported_type!(deserialize_ignored_any, "ignored_any"); parse_single_value!(deserialize_bool); parse_single_value!(deserialize_i8); parse_single_value!(deserialize_i16); parse_single_value!(deserialize_i32); parse_single_value!(deserialize_i64); parse_single_value!(deserialize_u8); parse_single_value!(deserialize_u16); parse_single_value!(deserialize_u32); parse_single_value!(deserialize_u64); parse_single_value!(deserialize_f32); parse_single_value!(deserialize_f64); parse_single_value!(deserialize_str); parse_single_value!(deserialize_string); parse_single_value!(deserialize_bytes); parse_single_value!(deserialize_byte_buf); parse_single_value!(deserialize_char); } struct ParamsDeserializer<'de, T: ResourcePath> { params: PathIter<'de, T>, current: Option<(&'de str, &'de str)>, } impl<'de, T: ResourcePath> de::MapAccess<'de> for ParamsDeserializer<'de, T> { type Error = de::value::Error; fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> where K: de::DeserializeSeed<'de>, { self.current = self.params.next().map(|ref item| (item.0, item.1)); match self.current { Some((key, _)) => Ok(Some(seed.deserialize(Key { key })?)), None => Ok(None), } } fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value, Self::Error> where V: de::DeserializeSeed<'de>, { if let Some((_, value)) = self.current.take() { seed.deserialize(Value { value }) } else { Err(de::value::Error::custom("unexpected item")) } } } struct Key<'de> { key: &'de str, } impl<'de> Deserializer<'de> for Key<'de> { type Error = de::value::Error; fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_str(self.key) } fn deserialize_any<V>(self, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("Unexpected")) } forward_to_deserialize_any! { bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 char str string bytes byte_buf option unit unit_struct newtype_struct seq tuple tuple_struct map struct enum ignored_any } } struct Value<'de> { value: &'de str, } impl<'de> Deserializer<'de> for Value<'de> { type Error = de::value::Error; parse_value!(deserialize_bool, visit_bool, "bool"); parse_value!(deserialize_i8, visit_i8, "i8"); parse_value!(deserialize_i16, visit_i16, "i16"); parse_value!(deserialize_i32, visit_i32, "i32"); parse_value!(deserialize_i64, visit_i64, "i64"); parse_value!(deserialize_u8, visit_u8, "u8"); parse_value!(deserialize_u16, visit_u16, "u16"); parse_value!(deserialize_u32, visit_u32, "u32"); parse_value!(deserialize_u64, visit_u64, "u64"); parse_value!(deserialize_f32, visit_f32, "f32"); parse_value!(deserialize_f64, visit_f64, "f64"); parse_value!(deserialize_char, visit_char, "char"); fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_unit() } fn deserialize_unit_struct<V>( self, _: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_unit() } fn deserialize_str<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match FULL_QUOTER.with(|q| q.requote_str_lossy(self.value)) { Some(s) => visitor.visit_string(s), None => visitor.visit_borrowed_str(self.value), } } fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { match FULL_QUOTER.with(|q| q.requote_str_lossy(self.value)) { Some(s) => visitor.visit_byte_buf(s.into()), None => visitor.visit_borrowed_bytes(self.value.as_bytes()), } } fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_bytes(visitor) } fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { self.deserialize_str(visitor) } fn deserialize_option<V>(self, visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_some(self) } fn deserialize_enum<V>( self, _: &'static str, _: &'static [&'static str], visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_enum(ValueEnum { value: self.value }) } fn deserialize_newtype_struct<V>( self, _: &'static str, visitor: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { visitor.visit_newtype_struct(self) } fn deserialize_tuple<V>(self, _: usize, _: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("unsupported type: tuple")) } fn deserialize_struct<V>( self, _: &'static str, _: &'static [&'static str], _: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("unsupported type: struct")) } fn deserialize_tuple_struct<V>( self, _: &'static str, _: usize, _: V, ) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("unsupported type: tuple struct")) } unsupported_type!(deserialize_any, "any"); unsupported_type!(deserialize_seq, "seq"); unsupported_type!(deserialize_map, "map"); unsupported_type!(deserialize_identifier, "identifier"); } struct ParamsSeq<'de, T: ResourcePath> { params: PathIter<'de, T>, } impl<'de, T: ResourcePath> de::SeqAccess<'de> for ParamsSeq<'de, T> { type Error = de::value::Error; fn next_element_seed<U>(&mut self, seed: U) -> Result<Option<U::Value>, Self::Error> where U: de::DeserializeSeed<'de>, { match self.params.next() { Some(item) => Ok(Some(seed.deserialize(Value { value: item.1 })?)), None => Ok(None), } } } struct ValueEnum<'de> { value: &'de str, } impl<'de> de::EnumAccess<'de> for ValueEnum<'de> { type Error = de::value::Error; type Variant = UnitVariant; fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> where V: de::DeserializeSeed<'de>, { Ok((seed.deserialize(Key { key: self.value })?, UnitVariant)) } } struct UnitVariant; impl<'de> de::VariantAccess<'de> for UnitVariant { type Error = de::value::Error; fn unit_variant(self) -> Result<(), Self::Error> { Ok(()) } fn newtype_variant_seed<T>(self, _seed: T) -> Result<T::Value, Self::Error> where T: de::DeserializeSeed<'de>, { Err(de::value::Error::custom("not supported")) } fn tuple_variant<V>(self, _len: usize, _visitor: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("not supported")) } fn struct_variant<V>(self, _: &'static [&'static str], _: V) -> Result<V::Value, Self::Error> where V: Visitor<'de>, { Err(de::value::Error::custom("not supported")) } } #[cfg(test)] mod tests { use serde::Deserialize; use super::*; use crate::{router::Router, ResourceDef}; #[derive(Deserialize)] struct MyStruct { key: String, value: String, } #[derive(Debug, Deserialize)] struct Test1(String, u32); #[derive(Debug, Deserialize)] struct Test2 { key: String, value: u32, } #[derive(Debug, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] enum TestEnum { Val1, Val2, } #[derive(Debug, Deserialize)] struct Test3 { val: TestEnum, } #[test] fn test_request_extract() { let mut router = Router::<()>::build(); router.path("/{key}/{value}/", ()); let router = router.finish(); let mut path = Path::new("/name/user1/"); assert!(router.recognize(&mut path).is_some()); let s: MyStruct = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.key, "name"); assert_eq!(s.value, "user1"); let s: (String, String) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.0, "name"); assert_eq!(s.1, "user1"); let mut router = Router::<()>::build(); router.path("/{key}/{value}/", ()); let router = router.finish(); let mut path = Path::new("/name/32/"); assert!(router.recognize(&mut path).is_some()); let s: Test1 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.0, "name"); assert_eq!(s.1, 32); let s: Test2 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.key, "name"); assert_eq!(s.value, 32); let s: (String, u8) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(s.0, "name"); assert_eq!(s.1, 32); let res: Vec<String> = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(res[0], "name".to_owned()); assert_eq!(res[1], "32".to_owned()); } #[test] fn test_extract_path_single() { let mut router = Router::<()>::build(); router.path("/{value}/", ()); let router = router.finish(); let mut path = Path::new("/32/"); assert!(router.recognize(&mut path).is_some()); let i: i8 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(i, 32); } #[test] fn test_extract_enum() { let mut router = Router::<()>::build(); router.path("/{val}/", ()); let router = router.finish(); let mut path = Path::new("/val1/"); assert!(router.recognize(&mut path).is_some()); let i: TestEnum = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(i, TestEnum::Val1); let mut router = Router::<()>::build(); router.path("/{val1}/{val2}/", ()); let router = router.finish(); let mut path = Path::new("/val1/val2/"); assert!(router.recognize(&mut path).is_some()); let i: (TestEnum, TestEnum) = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(i, (TestEnum::Val1, TestEnum::Val2)); } #[test] fn test_extract_enum_value() { let mut router = Router::<()>::build(); router.path("/{val}/", ()); let router = router.finish(); let mut path = Path::new("/val1/"); assert!(router.recognize(&mut path).is_some()); let i: Test3 = de::Deserialize::deserialize(PathDeserializer::new(&path)).unwrap(); assert_eq!(i.val, TestEnum::Val1); let mut path = Path::new("/val3/"); assert!(router.recognize(&mut path).is_some()); let i: Result<Test3, de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(i.is_err()); assert!(format!("{:?}", i).contains("unknown variant")); } #[test] fn test_extract_errors() { let mut router = Router::<()>::build(); router.path("/{value}/", ()); let router = router.finish(); let mut path = Path::new("/name/"); assert!(router.recognize(&mut path).is_some()); let s: Result<Test1, de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(s.is_err()); assert!(format!("{:?}", s).contains("wrong number of parameters")); let s: Result<Test2, de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(s.is_err()); assert!(format!("{:?}", s).contains("can not parse")); let s: Result<(String, String), de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(s.is_err()); assert!(format!("{:?}", s).contains("wrong number of parameters")); let s: Result<u32, de::value::Error> = de::Deserialize::deserialize(PathDeserializer::new(&path)); assert!(s.is_err()); assert!(format!("{:?}", s).contains("can not parse")); } #[test] fn deserialize_path_decode_string() { let rdef = ResourceDef::new("/{key}"); let mut path = Path::new("/%25"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let segment: String = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(segment, "%"); let mut path = Path::new("/%2F"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let segment: String = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(segment, "/") } #[test] fn deserialize_path_decode_seq() { let rdef = ResourceDef::new("/{key}/{value}"); let mut path = Path::new("/%30%25/%30%2F"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let segment: (String, String) = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(segment.0, "0%"); assert_eq!(segment.1, "0/"); } #[test] fn deserialize_path_decode_map() { #[derive(Deserialize)] struct Vals { key: String, value: String, } let rdef = ResourceDef::new("/{key}/{value}"); let mut path = Path::new("/%25/%2F"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let vals: Vals = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(vals.key, "%"); assert_eq!(vals.value, "/"); } #[test] fn deserialize_borrowed() { #[derive(Debug, Deserialize)] struct Params<'a> { val: &'a str, } let rdef = ResourceDef::new("/{val}"); let mut path = Path::new("/X"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); let params: Params<'_> = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(params.val, "X"); let de = PathDeserializer::new(&path); let params: &str = serde::Deserialize::deserialize(de).unwrap(); assert_eq!(params, "X"); let mut path = Path::new("/%2F"); rdef.capture_match_info(&mut path); let de = PathDeserializer::new(&path); assert!(<Params<'_> as serde::Deserialize>::deserialize(de).is_err()); let de = PathDeserializer::new(&path); assert!(<&str as serde::Deserialize>::deserialize(de).is_err()); } // #[test] // fn test_extract_path_decode() { // let mut router = Router::<()>::default(); // router.register_resource(Resource::new(ResourceDef::new("/{value}/"))); // macro_rules! test_single_value { // ($value:expr, $expected:expr) => {{ // let req = TestRequest::with_uri($value).finish(); // let info = router.recognize(&req, &(), 0); // let req = req.with_route_info(info); // assert_eq!( // *Path::<String>::from_request(&req, &PathConfig::default()).unwrap(), // $expected // ); // }}; // } // test_single_value!("/%25/", "%"); // test_single_value!("/%40%C2%A3%24%25%5E%26%2B%3D/", "@£$%^&+="); // test_single_value!("/%2B/", "+"); // test_single_value!("/%252B/", "%2B"); // test_single_value!("/%2F/", "/"); // test_single_value!("/%252F/", "%2F"); // test_single_value!( // "/http%3A%2F%2Flocalhost%3A80%2Ffoo/", // "http://localhost:80/foo" // ); // test_single_value!("/%2Fvar%2Flog%2Fsyslog/", "/var/log/syslog"); // test_single_value!( // "/http%3A%2F%2Flocalhost%3A80%2Ffile%2F%252Fvar%252Flog%252Fsyslog/", // "http://localhost:80/file/%2Fvar%2Flog%2Fsyslog" // ); // let req = TestRequest::with_uri("/%25/7/?id=test").finish(); // let mut router = Router::<()>::default(); // router.register_resource(Resource::new(ResourceDef::new("/{key}/{value}/"))); // let info = router.recognize(&req, &(), 0); // let req = req.with_route_info(info); // let s = Path::<Test2>::from_request(&req, &PathConfig::default()).unwrap(); // assert_eq!(s.key, "%"); // assert_eq!(s.value, 7); // let s = Path::<(String, String)>::from_request(&req, &PathConfig::default()).unwrap(); // assert_eq!(s.0, "%"); // assert_eq!(s.1, "7"); // } // #[test] // fn test_extract_path_no_decode() { // let mut router = Router::<()>::default(); // router.register_resource(Resource::new(ResourceDef::new("/{value}/"))); // let req = TestRequest::with_uri("/%25/").finish(); // let info = router.recognize(&req, &(), 0); // let req = req.with_route_info(info); // assert_eq!( // *Path::<String>::from_request(&req, &&PathConfig::default().disable_decoding()) // .unwrap(), // "%25" // ); // } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/benches/router.rs
actix-router/benches/router.rs
//! Based on https://github.com/ibraheemdev/matchit/blob/master/benches/bench.rs use criterion::{black_box, criterion_group, criterion_main, Criterion}; macro_rules! register { (colon) => {{ register!(finish => ":p1", ":p2", ":p3", ":p4") }}; (brackets) => {{ register!(finish => "{p1}", "{p2}", "{p3}", "{p4}") }}; (regex) => {{ register!(finish => "(.*)", "(.*)", "(.*)", "(.*)") }}; (finish => $p1:literal, $p2:literal, $p3:literal, $p4:literal) => {{ #[expect(clippy::useless_concat)] let arr = [ concat!("/authorizations"), concat!("/authorizations/", $p1), concat!("/applications/", $p1, "/tokens/", $p2), concat!("/events"), concat!("/repos/", $p1, "/", $p2, "/events"), concat!("/networks/", $p1, "/", $p2, "/events"), concat!("/orgs/", $p1, "/events"), concat!("/users/", $p1, "/received_events"), concat!("/users/", $p1, "/received_events/public"), concat!("/users/", $p1, "/events"), concat!("/users/", $p1, "/events/public"), concat!("/users/", $p1, "/events/orgs/", $p2), concat!("/feeds"), concat!("/notifications"), concat!("/repos/", $p1, "/", $p2, "/notifications"), concat!("/notifications/threads/", $p1), concat!("/notifications/threads/", $p1, "/subscription"), concat!("/repos/", $p1, "/", $p2, "/stargazers"), concat!("/users/", $p1, "/starred"), concat!("/user/starred"), concat!("/user/starred/", $p1, "/", $p2), concat!("/repos/", $p1, "/", $p2, "/subscribers"), concat!("/users/", $p1, "/subscriptions"), concat!("/user/subscriptions"), concat!("/repos/", $p1, "/", $p2, "/subscription"), concat!("/user/subscriptions/", $p1, "/", $p2), concat!("/users/", $p1, "/gists"), concat!("/gists"), concat!("/gists/", $p1), concat!("/gists/", $p1, "/star"), concat!("/repos/", $p1, "/", $p2, "/git/blobs/", $p3), concat!("/repos/", $p1, "/", $p2, "/git/commits/", $p3), concat!("/repos/", $p1, "/", $p2, "/git/refs"), concat!("/repos/", $p1, "/", $p2, "/git/tags/", $p3), concat!("/repos/", $p1, "/", $p2, "/git/trees/", $p3), concat!("/issues"), concat!("/user/issues"), concat!("/orgs/", $p1, "/issues"), concat!("/repos/", $p1, "/", $p2, "/issues"), concat!("/repos/", $p1, "/", $p2, "/issues/", $p3), concat!("/repos/", $p1, "/", $p2, "/assignees"), concat!("/repos/", $p1, "/", $p2, "/assignees/", $p3), concat!("/repos/", $p1, "/", $p2, "/issues/", $p3, "/comments"), concat!("/repos/", $p1, "/", $p2, "/issues/", $p3, "/events"), concat!("/repos/", $p1, "/", $p2, "/labels"), concat!("/repos/", $p1, "/", $p2, "/labels/", $p3), concat!("/repos/", $p1, "/", $p2, "/issues/", $p3, "/labels"), concat!("/repos/", $p1, "/", $p2, "/milestones/", $p3, "/labels"), concat!("/repos/", $p1, "/", $p2, "/milestones/"), concat!("/repos/", $p1, "/", $p2, "/milestones/", $p3), concat!("/emojis"), concat!("/gitignore/templates"), concat!("/gitignore/templates/", $p1), concat!("/meta"), concat!("/rate_limit"), concat!("/users/", $p1, "/orgs"), concat!("/user/orgs"), concat!("/orgs/", $p1), concat!("/orgs/", $p1, "/members"), concat!("/orgs/", $p1, "/members", $p2), concat!("/orgs/", $p1, "/public_members"), concat!("/orgs/", $p1, "/public_members/", $p2), concat!("/orgs/", $p1, "/teams"), concat!("/teams/", $p1), concat!("/teams/", $p1, "/members"), concat!("/teams/", $p1, "/members", $p2), concat!("/teams/", $p1, "/repos"), concat!("/teams/", $p1, "/repos/", $p2, "/", $p3), concat!("/user/teams"), concat!("/repos/", $p1, "/", $p2, "/pulls"), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3, "/commits"), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3, "/files"), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3, "/merge"), concat!("/repos/", $p1, "/", $p2, "/pulls/", $p3, "/comments"), concat!("/user/repos"), concat!("/users/", $p1, "/repos"), concat!("/orgs/", $p1, "/repos"), concat!("/repositories"), concat!("/repos/", $p1, "/", $p2), concat!("/repos/", $p1, "/", $p2, "/contributors"), concat!("/repos/", $p1, "/", $p2, "/languages"), concat!("/repos/", $p1, "/", $p2, "/teams"), concat!("/repos/", $p1, "/", $p2, "/tags"), concat!("/repos/", $p1, "/", $p2, "/branches"), concat!("/repos/", $p1, "/", $p2, "/branches/", $p3), concat!("/repos/", $p1, "/", $p2, "/collaborators"), concat!("/repos/", $p1, "/", $p2, "/collaborators/", $p3), concat!("/repos/", $p1, "/", $p2, "/comments"), concat!("/repos/", $p1, "/", $p2, "/commits/", $p3, "/comments"), concat!("/repos/", $p1, "/", $p2, "/commits"), concat!("/repos/", $p1, "/", $p2, "/commits/", $p3), concat!("/repos/", $p1, "/", $p2, "/readme"), concat!("/repos/", $p1, "/", $p2, "/keys"), concat!("/repos/", $p1, "/", $p2, "/keys", $p3), concat!("/repos/", $p1, "/", $p2, "/downloads"), concat!("/repos/", $p1, "/", $p2, "/downloads", $p3), concat!("/repos/", $p1, "/", $p2, "/forks"), concat!("/repos/", $p1, "/", $p2, "/hooks"), concat!("/repos/", $p1, "/", $p2, "/hooks", $p3), concat!("/repos/", $p1, "/", $p2, "/releases"), concat!("/repos/", $p1, "/", $p2, "/releases/", $p3), concat!("/repos/", $p1, "/", $p2, "/releases/", $p3, "/assets"), concat!("/repos/", $p1, "/", $p2, "/stats/contributors"), concat!("/repos/", $p1, "/", $p2, "/stats/commit_activity"), concat!("/repos/", $p1, "/", $p2, "/stats/code_frequency"), concat!("/repos/", $p1, "/", $p2, "/stats/participation"), concat!("/repos/", $p1, "/", $p2, "/stats/punch_card"), concat!("/repos/", $p1, "/", $p2, "/statuses/", $p3), concat!("/search/repositories"), concat!("/search/code"), concat!("/search/issues"), concat!("/search/users"), concat!("/legacy/issues/search/", $p1, "/", $p2, "/", $p3, "/", $p4), concat!("/legacy/repos/search/", $p1), concat!("/legacy/user/search/", $p1), concat!("/legacy/user/email/", $p1), concat!("/users/", $p1), concat!("/user"), concat!("/users"), concat!("/user/emails"), concat!("/users/", $p1, "/followers"), concat!("/user/followers"), concat!("/users/", $p1, "/following"), concat!("/user/following"), concat!("/user/following/", $p1), concat!("/users/", $p1, "/following", $p2), concat!("/users/", $p1, "/keys"), concat!("/user/keys"), concat!("/user/keys/", $p1), ]; IntoIterator::into_iter(arr) }}; } fn call() -> impl Iterator<Item = &'static str> { let arr = [ "/authorizations", "/user/repos", "/repos/rust-lang/rust/stargazers", "/orgs/rust-lang/public_members/nikomatsakis", "/repos/rust-lang/rust/releases/1.51.0", ]; IntoIterator::into_iter(arr) } fn compare_routers(c: &mut Criterion) { let mut group = c.benchmark_group("Compare Routers"); let mut actix = actix_router::Router::<bool>::build(); for route in register!(brackets) { actix.path(route, true); } let actix = actix.finish(); group.bench_function("actix", |b| { b.iter(|| { for route in call() { let mut path = actix_router::Path::new(route); black_box(actix.recognize(&mut path).unwrap()); } }); }); let regex_set = regex::RegexSet::new(register!(regex)).unwrap(); group.bench_function("regex", |b| { b.iter(|| { for route in call() { black_box(regex_set.matches(route)); } }); }); group.finish(); } criterion_group!(benches, compare_routers); criterion_main!(benches);
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-router/benches/quoter.rs
actix-router/benches/quoter.rs
use std::{borrow::Cow, fmt::Write as _}; use criterion::{black_box, criterion_group, criterion_main, Criterion}; fn compare_quoters(c: &mut Criterion) { let mut group = c.benchmark_group("Compare Quoters"); let quoter = actix_router::Quoter::new(b"", b""); let path_quoted = (0..=0x7f).fold(String::new(), |mut buf, c| { write!(&mut buf, "%{:02X}", c).unwrap(); buf }); let path_unquoted = ('\u{00}'..='\u{7f}').collect::<String>(); group.bench_function("quoter_unquoted", |b| { b.iter(|| { for _ in 0..10 { black_box(quoter.requote(path_unquoted.as_bytes())); } }); }); group.bench_function("percent_encode_unquoted", |b| { b.iter(|| { for _ in 0..10 { let decode = percent_encoding::percent_decode(path_unquoted.as_bytes()); black_box(Into::<Cow<'_, [u8]>>::into(decode)); } }); }); group.bench_function("quoter_quoted", |b| { b.iter(|| { for _ in 0..10 { black_box(quoter.requote(path_quoted.as_bytes())); } }); }); group.bench_function("percent_encode_quoted", |b| { b.iter(|| { for _ in 0..10 { let decode = percent_encoding::percent_decode(path_quoted.as_bytes()); black_box(Into::<Cow<'_, [u8]>>::into(decode)); } }); }); group.finish(); } criterion_group!(benches, compare_quoters); criterion_main!(benches);
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/config.rs
actix-web/src/config.rs
use std::{net::SocketAddr, rc::Rc}; use actix_service::{boxed, IntoServiceFactory, ServiceFactory, ServiceFactoryExt as _}; use crate::{ data::Data, dev::{Extensions, ResourceDef}, error::Error, guard::Guard, resource::Resource, rmap::ResourceMap, route::Route, service::{ AppServiceFactory, BoxedHttpServiceFactory, HttpServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse, }, }; type Guards = Vec<Box<dyn Guard>>; /// Application configuration pub struct AppService { config: AppConfig, root: bool, default: Rc<BoxedHttpServiceFactory>, #[allow(clippy::type_complexity)] services: Vec<( ResourceDef, BoxedHttpServiceFactory, Option<Guards>, Option<Rc<ResourceMap>>, )>, } impl AppService { /// Crate server settings instance. pub(crate) fn new(config: AppConfig, default: Rc<BoxedHttpServiceFactory>) -> Self { AppService { config, default, root: true, services: Vec::new(), } } /// Check if root is being configured pub fn is_root(&self) -> bool { self.root } #[allow(clippy::type_complexity)] pub(crate) fn into_services( self, ) -> ( AppConfig, Vec<( ResourceDef, BoxedHttpServiceFactory, Option<Guards>, Option<Rc<ResourceMap>>, )>, ) { (self.config, self.services) } /// Clones inner config and default service, returning new `AppService` with empty service list /// marked as non-root. pub(crate) fn clone_config(&self) -> Self { AppService { config: self.config.clone(), default: Rc::clone(&self.default), services: Vec::new(), root: false, } } /// Returns reference to configuration. pub fn config(&self) -> &AppConfig { &self.config } /// Returns default handler factory. pub fn default_service(&self) -> Rc<BoxedHttpServiceFactory> { Rc::clone(&self.default) } /// Register HTTP service. pub fn register_service<F, S>( &mut self, rdef: ResourceDef, guards: Option<Vec<Box<dyn Guard>>>, factory: F, nested: Option<Rc<ResourceMap>>, ) where F: IntoServiceFactory<S, ServiceRequest>, S: ServiceFactory< ServiceRequest, Response = ServiceResponse, Error = Error, Config = (), InitError = (), > + 'static, { self.services .push((rdef, boxed::factory(factory.into_factory()), guards, nested)); } } /// Application connection config. #[derive(Debug, Clone)] pub struct AppConfig { secure: bool, host: String, addr: SocketAddr, } impl AppConfig { pub(crate) fn new(secure: bool, host: String, addr: SocketAddr) -> Self { AppConfig { secure, host, addr } } /// Needed in actix-test crate. Semver exempt. #[doc(hidden)] pub fn __priv_test_new(secure: bool, host: String, addr: SocketAddr) -> Self { AppConfig::new(secure, host, addr) } /// Server host name. /// /// Host name is used by application router as a hostname for URL generation. /// Check [ConnectionInfo](super::dev::ConnectionInfo::host()) /// documentation for more information. /// /// By default host name is set to a "localhost" value. pub fn host(&self) -> &str { &self.host } /// Returns true if connection is secure (i.e., running over `https:`). pub fn secure(&self) -> bool { self.secure } /// Returns the socket address of the local half of this TCP connection. pub fn local_addr(&self) -> SocketAddr { self.addr } #[cfg(test)] pub(crate) fn set_host(&mut self, host: &str) { host.clone_into(&mut self.host); } } impl Default for AppConfig { /// Returns the default AppConfig. /// Note: The included socket address is "127.0.0.1". /// /// 127.0.0.1: non-routable meta address that denotes an unknown, invalid or non-applicable target. /// If you need a service only accessed by itself, use a loopback address. /// A loopback address for IPv4 is any loopback address that begins with "127". /// Loopback addresses should be only used to test your application locally. /// The default configuration provides a loopback address. /// /// 0.0.0.0: if configured to use this special address, the application will listen to any IP address configured on the machine. fn default() -> Self { AppConfig::new( false, "localhost:8080".to_owned(), "127.0.0.1:8080".parse().unwrap(), ) } } /// Enables parts of app configuration to be declared separately from the app itself. Helpful for /// modularizing large applications. /// /// Merge a `ServiceConfig` into an app using [`App::configure`](crate::App::configure). Scope and /// resources services have similar methods. /// /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// // this function could be located in different module /// fn config(cfg: &mut web::ServiceConfig) { /// cfg.service(web::resource("/test") /// .route(web::get().to(|| HttpResponse::Ok())) /// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) /// ); /// } /// /// // merge `/test` routes from config function to App /// App::new().configure(config); /// ``` pub struct ServiceConfig { pub(crate) services: Vec<Box<dyn AppServiceFactory>>, pub(crate) external: Vec<ResourceDef>, pub(crate) app_data: Extensions, pub(crate) default: Option<Rc<BoxedHttpServiceFactory>>, } impl ServiceConfig { pub(crate) fn new() -> Self { Self { services: Vec::new(), external: Vec::new(), app_data: Extensions::new(), default: None, } } /// Add shared app data item. /// /// Counterpart to [`App::data()`](crate::App::data). #[deprecated(since = "4.0.0", note = "Use `.app_data(Data::new(val))` instead.")] pub fn data<U: 'static>(&mut self, data: U) -> &mut Self { self.app_data(Data::new(data)); self } /// Add arbitrary app data item. /// /// Counterpart to [`App::app_data()`](crate::App::app_data). pub fn app_data<U: 'static>(&mut self, ext: U) -> &mut Self { self.app_data.insert(ext); self } /// Default service to be used if no matching resource could be found. /// /// Counterpart to [`App::default_service()`](crate::App::default_service). pub fn default_service<F, U>(&mut self, f: F) -> &mut Self where F: IntoServiceFactory<U, ServiceRequest>, U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static, U::InitError: std::fmt::Debug, { let svc = f .into_factory() .map_init_err(|err| log::error!("Can not construct default service: {:?}", err)); self.default = Some(Rc::new(boxed::factory(svc))); self } /// Run external configuration as part of the application building process /// /// Counterpart to [`App::configure()`](crate::App::configure) that allows for easy nesting. pub fn configure<F>(&mut self, f: F) -> &mut Self where F: FnOnce(&mut ServiceConfig), { f(self); self } /// Configure route for a specific path. /// /// Counterpart to [`App::route()`](crate::App::route). pub fn route(&mut self, path: &str, mut route: Route) -> &mut Self { self.service( Resource::new(path) .add_guards(route.take_guards()) .route(route), ) } /// Register HTTP service factory. /// /// Counterpart to [`App::service()`](crate::App::service). pub fn service<F>(&mut self, factory: F) -> &mut Self where F: HttpServiceFactory + 'static, { self.services .push(Box::new(ServiceFactoryWrapper::new(factory))); self } /// Register an external resource. /// /// External resources are useful for URL generation purposes only and are never considered for /// matching at request time. Calls to [`HttpRequest::url_for()`](crate::HttpRequest::url_for) /// will work as expected. /// /// Counterpart to [`App::external_resource()`](crate::App::external_resource). pub fn external_resource<N, U>(&mut self, name: N, url: U) -> &mut Self where N: AsRef<str>, U: AsRef<str>, { let mut rdef = ResourceDef::new(url.as_ref()); rdef.set_name(name.as_ref()); self.external.push(rdef); self } } #[cfg(test)] mod tests { use actix_service::Service; use bytes::Bytes; use super::*; use crate::{ http::{Method, StatusCode}, test::{assert_body_eq, call_service, init_service, read_body, TestRequest}, web, App, HttpRequest, HttpResponse, }; // allow deprecated `ServiceConfig::data` #[allow(deprecated)] #[actix_rt::test] async fn test_data() { let cfg = |cfg: &mut ServiceConfig| { cfg.data(10usize); cfg.app_data(15u8); }; let srv = init_service(App::new().configure(cfg).service(web::resource("/").to( |_: web::Data<usize>, req: HttpRequest| { assert_eq!(*req.app_data::<u8>().unwrap(), 15u8); HttpResponse::Ok() }, ))) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_external_resource() { let srv = init_service( App::new() .configure(|cfg| { cfg.external_resource("youtube", "https://youtube.com/watch/{video_id}"); }) .route( "/test", web::get().to(|req: HttpRequest| { HttpResponse::Ok() .body(req.url_for("youtube", ["12345"]).unwrap().to_string()) }), ), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345")); } #[actix_rt::test] async fn registers_default_service() { let srv = init_service( App::new() .configure(|cfg| { cfg.default_service( web::get().to(|| HttpResponse::NotFound().body("four oh four")), ); }) .service(web::scope("/scoped").configure(|cfg| { cfg.default_service( web::get().to(|| HttpResponse::NotFound().body("scoped four oh four")), ); })), ) .await; // app registers default service let req = TestRequest::with_uri("/path/i/did/not-configure").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"four oh four")); // scope registers default service let req = TestRequest::with_uri("/scoped/path/i/did/not-configure").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"scoped four oh four")); } #[actix_rt::test] async fn test_service() { let srv = init_service(App::new().configure(|cfg| { cfg.service(web::resource("/test").route(web::get().to(HttpResponse::Created))) .route("/index.html", web::get().to(HttpResponse::Ok)); })) .await; let req = TestRequest::with_uri("/test") .method(Method::GET) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::CREATED); let req = TestRequest::with_uri("/index.html") .method(Method::GET) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn nested_service_configure() { fn cfg_root(cfg: &mut ServiceConfig) { cfg.configure(cfg_sub); } fn cfg_sub(cfg: &mut ServiceConfig) { cfg.route("/", web::get().to(|| async { "hello world" })); } let srv = init_service(App::new().configure(cfg_root)).await; let req = TestRequest::with_uri("/").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); assert_body_eq!(res, b"hello world"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/app.rs
actix-web/src/app.rs
use std::{cell::RefCell, fmt, future::Future, rc::Rc}; use actix_http::{body::MessageBody, Extensions, Request}; use actix_service::{ apply, apply_fn_factory, boxed, IntoServiceFactory, ServiceFactory, ServiceFactoryExt, Transform, }; use futures_util::FutureExt as _; use crate::{ app_service::{AppEntry, AppInit, AppRoutingFactory}, config::ServiceConfig, data::{Data, DataFactory, FnDataFactory}, dev::ResourceDef, error::Error, resource::Resource, route::Route, service::{ AppServiceFactory, BoxedHttpServiceFactory, HttpServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse, }, }; /// The top-level builder for an Actix Web application. pub struct App<T> { endpoint: T, services: Vec<Box<dyn AppServiceFactory>>, default: Option<Rc<BoxedHttpServiceFactory>>, factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>, data_factories: Vec<FnDataFactory>, external: Vec<ResourceDef>, extensions: Extensions, } impl App<AppEntry> { /// Create application builder. Application can be configured with a builder-like pattern. #[allow(clippy::new_without_default)] pub fn new() -> Self { let factory_ref = Rc::new(RefCell::new(None)); App { endpoint: AppEntry::new(Rc::clone(&factory_ref)), data_factories: Vec::new(), services: Vec::new(), default: None, factory_ref, external: Vec::new(), extensions: Extensions::new(), } } } impl<T> App<T> where T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>, { /// Set application (root level) data. /// /// Application data stored with `App::app_data()` method is available through the /// [`HttpRequest::app_data`](crate::HttpRequest::app_data) method at runtime. /// /// # [`Data<T>`] /// Any [`Data<T>`] type added here can utilize its extractor implementation in handlers. /// Types not wrapped in `Data<T>` cannot use this extractor. See [its docs](Data<T>) for more /// about its usage and patterns. /// /// ``` /// use std::cell::Cell; /// use actix_web::{web, App, HttpRequest, HttpResponse, Responder}; /// /// struct MyData { /// count: std::cell::Cell<usize>, /// } /// /// async fn handler(req: HttpRequest, counter: web::Data<MyData>) -> impl Responder { /// // note this cannot use the Data<T> extractor because it was not added with it /// let incr = *req.app_data::<usize>().unwrap(); /// assert_eq!(incr, 3); /// /// // update counter using other value from app data /// counter.count.set(counter.count.get() + incr); /// /// HttpResponse::Ok().body(counter.count.get().to_string()) /// } /// /// let app = App::new().service( /// web::resource("/") /// .app_data(3usize) /// .app_data(web::Data::new(MyData { count: Default::default() })) /// .route(web::get().to(handler)) /// ); /// ``` /// /// # Shared Mutable State /// [`HttpServer::new`](crate::HttpServer::new) accepts an application factory rather than an /// application instance; the factory closure is called on each worker thread independently. /// Therefore, if you want to share a data object between different workers, a shareable object /// needs to be created first, outside the `HttpServer::new` closure and cloned into it. /// [`Data<T>`] is an example of such a sharable object. /// /// ```ignore /// let counter = web::Data::new(AppStateWithCounter { /// counter: Mutex::new(0), /// }); /// /// HttpServer::new(move || { /// // move counter object into the closure and clone for each worker /// /// App::new() /// .app_data(counter.clone()) /// .route("/", web::get().to(handler)) /// }) /// ``` #[doc(alias = "manage")] pub fn app_data<U: 'static>(mut self, data: U) -> Self { self.extensions.insert(data); self } /// Add application (root) data after wrapping in `Data<T>`. /// /// Deprecated in favor of [`app_data`](Self::app_data). #[deprecated(since = "4.0.0", note = "Use `.app_data(Data::new(val))` instead.")] pub fn data<U: 'static>(self, data: U) -> Self { self.app_data(Data::new(data)) } /// Add application data factory that resolves asynchronously. /// /// Data items are constructed during application initialization, before the server starts /// accepting requests. /// /// The returned data value `D` is wrapped as [`Data<D>`]. pub fn data_factory<F, Out, D, E>(mut self, data: F) -> Self where F: Fn() -> Out + 'static, Out: Future<Output = Result<D, E>> + 'static, D: 'static, E: std::fmt::Debug, { self.data_factories.push(Box::new(move || { { let fut = data(); async move { match fut.await { Err(err) => { log::error!("Can not construct data instance: {err:?}"); Err(()) } Ok(data) => { let data: Box<dyn DataFactory> = Box::new(Data::new(data)); Ok(data) } } } } .boxed_local() })); self } /// Run external configuration as part of the application building /// process /// /// This function is useful for moving parts of configuration to a /// different module or even library. For example, /// some of the resource's configuration could be moved to different module. /// /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// // this function could be located in different module /// fn config(cfg: &mut web::ServiceConfig) { /// cfg.service(web::resource("/test") /// .route(web::get().to(|| HttpResponse::Ok())) /// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) /// ); /// } /// /// App::new() /// .configure(config) // <- register resources /// .route("/index.html", web::get().to(|| HttpResponse::Ok())); /// ``` pub fn configure<F>(mut self, f: F) -> Self where F: FnOnce(&mut ServiceConfig), { let mut cfg = ServiceConfig::new(); f(&mut cfg); self.services.extend(cfg.services); self.external.extend(cfg.external); self.extensions.extend(cfg.app_data); if let Some(default) = cfg.default { self.default = Some(default); } self } /// Configure route for a specific path. /// /// This is a simplified version of the `App::service()` method. /// This method can be used multiple times with same path, in that case /// multiple resources with one route would be registered for same resource path. /// /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// async fn index(data: web::Path<(String, String)>) -> &'static str { /// "Welcome!" /// } /// /// let app = App::new() /// .route("/test1", web::get().to(index)) /// .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed())); /// ``` pub fn route(self, path: &str, mut route: Route) -> Self { self.service( Resource::new(path) .add_guards(route.take_guards()) .route(route), ) } /// Register HTTP service. /// /// Http service is any type that implements `HttpServiceFactory` trait. /// /// Actix Web provides several services implementations: /// /// * *Resource* is an entry in resource table which corresponds to requested URL. /// * *Scope* is a set of resources with common root path. pub fn service<F>(mut self, factory: F) -> Self where F: HttpServiceFactory + 'static, { self.services .push(Box::new(ServiceFactoryWrapper::new(factory))); self } /// Default service that is invoked when no matching resource could be found. /// /// You can use a [`Route`] as default service. /// /// If a default service is not registered, an empty `404 Not Found` response will be sent to /// the client instead. /// /// # Examples /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// async fn index() -> &'static str { /// "Welcome!" /// } /// /// let app = App::new() /// .service(web::resource("/index.html").route(web::get().to(index))) /// .default_service(web::to(|| HttpResponse::NotFound())); /// ``` pub fn default_service<F, U>(mut self, svc: F) -> Self where F: IntoServiceFactory<U, ServiceRequest>, U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static, U::InitError: fmt::Debug, { let svc = svc.into_factory().map_init_err(|err| { log::error!("Can not construct default service: {err:?}"); }); self.default = Some(Rc::new(boxed::factory(svc))); self } /// Register an external resource. /// /// External resources are useful for URL generation purposes only /// and are never considered for matching at request time. Calls to /// `HttpRequest::url_for()` will work as expected. /// /// ``` /// use actix_web::{web, App, HttpRequest, HttpResponse, Result}; /// /// async fn index(req: HttpRequest) -> Result<HttpResponse> { /// let url = req.url_for("youtube", &["asdlkjqme"])?; /// assert_eq!(url.as_str(), "https://youtube.com/watch/asdlkjqme"); /// Ok(HttpResponse::Ok().into()) /// } /// /// let app = App::new() /// .service(web::resource("/index.html").route( /// web::get().to(index))) /// .external_resource("youtube", "https://youtube.com/watch/{video_id}"); /// ``` pub fn external_resource<N, U>(mut self, name: N, url: U) -> Self where N: AsRef<str>, U: AsRef<str>, { let mut rdef = ResourceDef::new(url.as_ref()); rdef.set_name(name.as_ref()); self.external.push(rdef); self } /// Registers an app-wide middleware. /// /// Registers middleware, in the form of a middleware component (type), that runs during /// inbound and/or outbound processing in the request life-cycle (request -> response), /// modifying request/response as necessary, across all requests managed by the `App`. /// /// Use middleware when you need to read or modify *every* request or response in some way. /// /// Middleware can be applied similarly to individual `Scope`s and `Resource`s. /// See [`Scope::wrap`](crate::Scope::wrap) and [`Resource::wrap`]. /// /// For more info on middleware take a look at the [`middleware` module][crate::middleware]. /// /// # Examples /// ``` /// use actix_web::{middleware, web, App}; /// /// async fn index() -> &'static str { /// "Welcome!" /// } /// /// let app = App::new() /// .wrap(middleware::Logger::default()) /// .route("/index.html", web::get().to(index)); /// ``` #[doc(alias = "middleware")] #[doc(alias = "use")] // nodejs terminology pub fn wrap<M, B>( self, mw: M, ) -> App< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, > where M: Transform< T::Service, ServiceRequest, Response = ServiceResponse<B>, Error = Error, InitError = (), > + 'static, B: MessageBody, { App { endpoint: apply(mw, self.endpoint), data_factories: self.data_factories, services: self.services, default: self.default, factory_ref: self.factory_ref, external: self.external, extensions: self.extensions, } } /// Registers an app-wide function middleware. /// /// `mw` is a closure that runs during inbound and/or outbound processing in the request /// life-cycle (request -> response), modifying request/response as necessary, across all /// requests handled by the `App`. /// /// Use middleware when you need to read or modify *every* request or response in some way. /// /// Middleware can also be applied to individual `Scope`s and `Resource`s. /// /// See [`App::wrap`] for details on how middlewares compose with each other. /// /// # Examples /// ``` /// use actix_web::{dev::Service as _, middleware, web, App}; /// use actix_web::http::header::{CONTENT_TYPE, HeaderValue}; /// /// async fn index() -> &'static str { /// "Welcome!" /// } /// /// let app = App::new() /// .wrap_fn(|req, srv| { /// let fut = srv.call(req); /// async { /// let mut res = fut.await?; /// res.headers_mut() /// .insert(CONTENT_TYPE, HeaderValue::from_static("text/plain")); /// Ok(res) /// } /// }) /// .route("/index.html", web::get().to(index)); /// ``` #[doc(alias = "middleware")] #[doc(alias = "use")] // nodejs terminology pub fn wrap_fn<F, R, B>( self, mw: F, ) -> App< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, > where F: Fn(ServiceRequest, &T::Service) -> R + Clone + 'static, R: Future<Output = Result<ServiceResponse<B>, Error>>, B: MessageBody, { App { endpoint: apply_fn_factory(self.endpoint, mw), data_factories: self.data_factories, services: self.services, default: self.default, factory_ref: self.factory_ref, external: self.external, extensions: self.extensions, } } } impl<T, B> IntoServiceFactory<AppInit<T, B>, Request> for App<T> where T: ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), > + 'static, B: MessageBody, { fn into_factory(self) -> AppInit<T, B> { AppInit { async_data_factories: self.data_factories.into_boxed_slice().into(), endpoint: self.endpoint, services: Rc::new(RefCell::new(self.services)), external: RefCell::new(self.external), default: self.default, factory_ref: self.factory_ref, extensions: RefCell::new(Some(self.extensions)), } } } #[cfg(test)] mod tests { use actix_service::Service as _; use actix_utils::future::{err, ok}; use bytes::Bytes; use super::*; use crate::{ http::{ header::{self, HeaderValue}, Method, StatusCode, }, middleware::DefaultHeaders, test::{call_service, init_service, read_body, try_init_service, TestRequest}, web, HttpRequest, HttpResponse, }; #[actix_rt::test] async fn test_default_resource() { let srv = init_service(App::new().service(web::resource("/test").to(HttpResponse::Ok))).await; let req = TestRequest::with_uri("/test").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/blah").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); let srv = init_service( App::new() .service(web::resource("/test").to(HttpResponse::Ok)) .service( web::resource("/test2") .default_service(|r: ServiceRequest| { ok(r.into_response(HttpResponse::Created())) }) .route(web::get().to(HttpResponse::Ok)), ) .default_service(|r: ServiceRequest| { ok(r.into_response(HttpResponse::MethodNotAllowed())) }), ) .await; let req = TestRequest::with_uri("/blah").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); let req = TestRequest::with_uri("/test2").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/test2") .method(Method::POST) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::CREATED); } // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_data_factory() { let srv = init_service( App::new() .data_factory(|| ok::<_, ()>(10usize)) .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let srv = init_service( App::new() .data_factory(|| ok::<_, ()>(10u32)) .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_data_factory_errors() { let srv = try_init_service( App::new() .data_factory(|| err::<u32, _>(())) .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())), ) .await; assert!(srv.is_err()); } #[actix_rt::test] async fn test_extension() { let srv = init_service(App::new().app_data(10usize).service(web::resource("/").to( |req: HttpRequest| { assert_eq!(*req.app_data::<usize>().unwrap(), 10); HttpResponse::Ok() }, ))) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_wrap() { let srv = init_service( App::new() .wrap( DefaultHeaders::new() .add((header::CONTENT_TYPE, HeaderValue::from_static("0001"))), ) .route("/test", web::get().to(HttpResponse::Ok)), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), HeaderValue::from_static("0001") ); } #[actix_rt::test] async fn test_router_wrap() { let srv = init_service( App::new() .route("/test", web::get().to(HttpResponse::Ok)) .wrap( DefaultHeaders::new() .add((header::CONTENT_TYPE, HeaderValue::from_static("0001"))), ), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), HeaderValue::from_static("0001") ); } #[actix_rt::test] async fn test_wrap_fn() { let srv = init_service( App::new() .wrap_fn(|req, srv| { let fut = srv.call(req); async move { let mut res = fut.await?; res.headers_mut() .insert(header::CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(res) } }) .service(web::resource("/test").to(HttpResponse::Ok)), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), HeaderValue::from_static("0001") ); } #[actix_rt::test] async fn test_router_wrap_fn() { let srv = init_service( App::new() .route("/test", web::get().to(HttpResponse::Ok)) .wrap_fn(|req, srv| { let fut = srv.call(req); async { let mut res = fut.await?; res.headers_mut() .insert(header::CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(res) } }), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), HeaderValue::from_static("0001") ); } #[actix_rt::test] async fn test_external_resource() { let srv = init_service( App::new() .external_resource("youtube", "https://youtube.com/watch/{video_id}") .route( "/test", web::get().to(|req: HttpRequest| { HttpResponse::Ok() .body(req.url_for("youtube", ["12345"]).unwrap().to_string()) }), ), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345")); } #[test] fn can_be_returned_from_fn() { /// compile-only test for returning app type from function pub fn my_app() -> App< impl ServiceFactory< ServiceRequest, Response = ServiceResponse<impl MessageBody>, Config = (), InitError = (), Error = Error, >, > { App::new() // logger can be removed without affecting the return type .wrap(crate::middleware::Logger::default()) .route("/", web::to(|| async { "hello" })) } #[allow(clippy::let_underscore_future)] let _ = init_service(my_app()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/dev.rs
actix-web/src/dev.rs
//! Lower-level types and re-exports. //! //! Most users will not have to interact with the types in this module, but it is useful for those //! writing extractors, middleware, libraries, or interacting with the service API directly. //! //! # Request Extractors //! - [`ConnectionInfo`]: Connection information //! - [`PeerAddr`]: Connection information #[cfg(feature = "__compress")] pub use actix_http::encoding::Decoder as Decompress; pub use actix_http::{Extensions, Payload, RequestHead, Response, ResponseHead}; use actix_router::Patterns; pub use actix_router::{Path, ResourceDef, ResourcePath, Url}; pub use actix_server::{Server, ServerHandle}; pub use actix_service::{ always_ready, fn_factory, fn_service, forward_ready, Service, ServiceFactory, Transform, }; #[doc(hidden)] pub use crate::handler::Handler; pub use crate::{ config::{AppConfig, AppService}, info::{ConnectionInfo, PeerAddr}, rmap::ResourceMap, service::{HttpServiceFactory, ServiceRequest, ServiceResponse, WebService}, types::{JsonBody, Readlines, UrlEncoded}, }; pub(crate) fn ensure_leading_slash(mut patterns: Patterns) -> Patterns { match &mut patterns { Patterns::Single(pat) => { if !pat.is_empty() && !pat.starts_with('/') { pat.insert(0, '/'); }; } Patterns::List(pats) => { for pat in pats { if !pat.is_empty() && !pat.starts_with('/') { pat.insert(0, '/'); }; } } } patterns }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/resource.rs
actix-web/src/resource.rs
use std::{cell::RefCell, fmt, future::Future, rc::Rc}; use actix_http::Extensions; use actix_router::{IntoPatterns, Patterns}; use actix_service::{ apply, apply_fn_factory, boxed, fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt, Transform, }; use futures_core::future::LocalBoxFuture; use futures_util::future::join_all; use crate::{ body::MessageBody, data::Data, dev::{ensure_leading_slash, AppService, ResourceDef}, guard::{self, Guard}, handler::Handler, http::header, route::{Route, RouteService}, service::{ BoxedHttpService, BoxedHttpServiceFactory, HttpServiceFactory, ServiceRequest, ServiceResponse, }, web, Error, FromRequest, HttpResponse, Responder, }; /// A collection of [`Route`]s that respond to the same path pattern. /// /// Resource in turn has at least one route. Route consists of an handlers objects and list of /// guards (objects that implement `Guard` trait). Resources and routes uses builder-like pattern /// for configuration. During request handling, the resource object iterates through all routes /// and checks guards for the specific route, if the request matches all the guards, then the route /// is considered matched and the route handler gets called. /// /// # Examples /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// let app = App::new().service( /// web::resource("/") /// .get(|| HttpResponse::Ok()) /// .post(|| async { "Hello World!" }) /// ); /// ``` /// /// If no matching route is found, an empty 405 response is returned which includes an /// [appropriate Allow header][RFC 9110 §15.5.6]. This default behavior can be overridden using /// [`default_service()`](Self::default_service). /// /// [RFC 9110 §15.5.6]: https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.6 pub struct Resource<T = ResourceEndpoint> { endpoint: T, rdef: Patterns, name: Option<String>, routes: Vec<Route>, app_data: Option<Extensions>, guards: Vec<Box<dyn Guard>>, default: BoxedHttpServiceFactory, factory_ref: Rc<RefCell<Option<ResourceFactory>>>, } impl Resource { /// Constructs new resource that matches a `path` pattern. pub fn new<T: IntoPatterns>(path: T) -> Resource { let factory_ref = Rc::new(RefCell::new(None)); Resource { routes: Vec::new(), rdef: path.patterns(), name: None, endpoint: ResourceEndpoint::new(Rc::clone(&factory_ref)), factory_ref, guards: Vec::new(), app_data: None, default: boxed::factory(fn_service(|req: ServiceRequest| async { use crate::HttpMessage as _; let allowed = req.extensions().get::<guard::RegisteredMethods>().cloned(); if let Some(methods) = allowed { Ok(req.into_response( HttpResponse::MethodNotAllowed() .insert_header(header::Allow(methods.0)) .finish(), )) } else { Ok(req.into_response(HttpResponse::MethodNotAllowed())) } })), } } } impl<T> Resource<T> where T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>, { /// Set resource name. /// /// Name is used for url generation. pub fn name(mut self, name: &str) -> Self { self.name = Some(name.to_string()); self } /// Add match guard to a resource. /// /// ``` /// use actix_web::{web, guard, App, HttpResponse}; /// /// async fn index(data: web::Path<(String, String)>) -> &'static str { /// "Welcome!" /// } /// /// let app = App::new() /// .service( /// web::resource("/app") /// .guard(guard::Header("content-type", "text/plain")) /// .route(web::get().to(index)) /// ) /// .service( /// web::resource("/app") /// .guard(guard::Header("content-type", "text/json")) /// .route(web::get().to(|| HttpResponse::MethodNotAllowed())) /// ); /// ``` pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self { self.guards.push(Box::new(guard)); self } pub(crate) fn add_guards(mut self, guards: Vec<Box<dyn Guard>>) -> Self { self.guards.extend(guards); self } /// Register a new route. /// /// ``` /// use actix_web::{web, guard, App, HttpResponse}; /// /// let app = App::new().service( /// web::resource("/").route( /// web::route() /// .guard(guard::Any(guard::Get()).or(guard::Put())) /// .guard(guard::Header("Content-Type", "text/plain")) /// .to(|| HttpResponse::Ok())) /// ); /// ``` /// /// Multiple routes could be added to a resource. Resource object uses /// match guards for route selection. /// /// ``` /// use actix_web::{web, guard, App}; /// /// let app = App::new().service( /// web::resource("/container/") /// .route(web::get().to(get_handler)) /// .route(web::post().to(post_handler)) /// .route(web::delete().to(delete_handler)) /// ); /// /// # async fn get_handler() -> impl actix_web::Responder { actix_web::HttpResponse::Ok() } /// # async fn post_handler() -> impl actix_web::Responder { actix_web::HttpResponse::Ok() } /// # async fn delete_handler() -> impl actix_web::Responder { actix_web::HttpResponse::Ok() } /// ``` pub fn route(mut self, route: Route) -> Self { self.routes.push(route); self } /// Add resource data. /// /// Data of different types from parent contexts will still be accessible. Any `Data<T>` types /// set here can be extracted in handlers using the `Data<T>` extractor. /// /// # Examples /// ``` /// use std::cell::Cell; /// use actix_web::{web, App, HttpRequest, HttpResponse, Responder}; /// /// struct MyData { /// count: std::cell::Cell<usize>, /// } /// /// async fn handler(req: HttpRequest, counter: web::Data<MyData>) -> impl Responder { /// // note this cannot use the Data<T> extractor because it was not added with it /// let incr = *req.app_data::<usize>().unwrap(); /// assert_eq!(incr, 3); /// /// // update counter using other value from app data /// counter.count.set(counter.count.get() + incr); /// /// HttpResponse::Ok().body(counter.count.get().to_string()) /// } /// /// let app = App::new().service( /// web::resource("/") /// .app_data(3usize) /// .app_data(web::Data::new(MyData { count: Default::default() })) /// .route(web::get().to(handler)) /// ); /// ``` #[doc(alias = "manage")] pub fn app_data<U: 'static>(mut self, data: U) -> Self { self.app_data .get_or_insert_with(Extensions::new) .insert(data); self } /// Add resource data after wrapping in `Data<T>`. /// /// Deprecated in favor of [`app_data`](Self::app_data). #[deprecated(since = "4.0.0", note = "Use `.app_data(Data::new(val))` instead.")] pub fn data<U: 'static>(self, data: U) -> Self { self.app_data(Data::new(data)) } /// Register a new route and add handler. This route matches all requests. /// /// ``` /// use actix_web::{App, HttpRequest, HttpResponse, web}; /// /// async fn index(req: HttpRequest) -> HttpResponse { /// todo!() /// } /// /// App::new().service(web::resource("/").to(index)); /// ``` /// /// This is shortcut for: /// /// ``` /// # use actix_web::*; /// # async fn index(req: HttpRequest) -> HttpResponse { todo!() } /// App::new().service(web::resource("/").route(web::route().to(index))); /// ``` pub fn to<F, Args>(mut self, handler: F) -> Self where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static, { self.routes.push(Route::new().to(handler)); self } /// Registers a resource middleware. /// /// `mw` is a middleware component (type), that can modify the request and response across all /// routes managed by this `Resource`. /// /// See [`App::wrap`](crate::App::wrap) for more details. #[doc(alias = "middleware")] #[doc(alias = "use")] // nodejs terminology pub fn wrap<M, B>( self, mw: M, ) -> Resource< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, > where M: Transform< T::Service, ServiceRequest, Response = ServiceResponse<B>, Error = Error, InitError = (), > + 'static, B: MessageBody, { Resource { endpoint: apply(mw, self.endpoint), rdef: self.rdef, name: self.name, guards: self.guards, routes: self.routes, default: self.default, app_data: self.app_data, factory_ref: self.factory_ref, } } /// Registers a resource function middleware. /// /// `mw` is a closure that runs during inbound and/or outbound processing in the request /// life-cycle (request -> response), modifying request/response as necessary, across all /// requests handled by the `Resource`. /// /// See [`App::wrap_fn`](crate::App::wrap_fn) for examples and more details. #[doc(alias = "middleware")] #[doc(alias = "use")] // nodejs terminology pub fn wrap_fn<F, R, B>( self, mw: F, ) -> Resource< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, > where F: Fn(ServiceRequest, &T::Service) -> R + Clone + 'static, R: Future<Output = Result<ServiceResponse<B>, Error>>, B: MessageBody, { Resource { endpoint: apply_fn_factory(self.endpoint, mw), rdef: self.rdef, name: self.name, guards: self.guards, routes: self.routes, default: self.default, app_data: self.app_data, factory_ref: self.factory_ref, } } /// Sets the default service to be used if no matching route is found. /// /// Unlike [`Scope`]s, a `Resource` does _not_ inherit its parent's default service. You can /// use a [`Route`] as default service. /// /// If a custom default service is not registered, an empty `405 Method Not Allowed` response /// with an appropriate Allow header will be sent instead. /// /// # Examples /// ``` /// use actix_web::{App, HttpResponse, web}; /// /// let resource = web::resource("/test") /// .route(web::get().to(HttpResponse::Ok)) /// .default_service(web::to(|| { /// HttpResponse::BadRequest() /// })); /// /// App::new().service(resource); /// ``` /// /// [`Scope`]: crate::Scope pub fn default_service<F, U>(mut self, f: F) -> Self where F: IntoServiceFactory<U, ServiceRequest>, U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static, U::InitError: fmt::Debug, { // create and configure default resource self.default = boxed::factory(f.into_factory().map_init_err(|err| { log::error!("Can not construct default service: {err:?}"); })); self } } macro_rules! route_shortcut { ($method_fn:ident, $method_upper:literal) => { #[doc = concat!(" Adds a ", $method_upper, " route.")] /// /// Use [`route`](Self::route) if you need to add additional guards. /// /// # Examples /// /// ``` /// # use actix_web::web; /// web::resource("/") #[doc = concat!(" .", stringify!($method_fn), "(|| async { \"Hello World!\" })")] /// # ; /// ``` pub fn $method_fn<F, Args>(self, handler: F) -> Self where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static, { self.route(web::$method_fn().to(handler)) } }; } /// Concise routes for well-known HTTP methods. impl<T> Resource<T> where T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>, { route_shortcut!(get, "GET"); route_shortcut!(post, "POST"); route_shortcut!(put, "PUT"); route_shortcut!(patch, "PATCH"); route_shortcut!(delete, "DELETE"); route_shortcut!(head, "HEAD"); route_shortcut!(trace, "TRACE"); } impl<T, B> HttpServiceFactory for Resource<T> where T: ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), > + 'static, B: MessageBody + 'static, { fn register(mut self, config: &mut AppService) { let guards = if self.guards.is_empty() { None } else { Some(std::mem::take(&mut self.guards)) }; let mut rdef = if config.is_root() || !self.rdef.is_empty() { ResourceDef::new(ensure_leading_slash(self.rdef.clone())) } else { ResourceDef::new(self.rdef.clone()) }; if let Some(ref name) = self.name { rdef.set_name(name); } *self.factory_ref.borrow_mut() = Some(ResourceFactory { routes: self.routes, default: self.default, }); let resource_data = self.app_data.map(Rc::new); // wraps endpoint service (including middleware) call and injects app data for this scope let endpoint = apply_fn_factory(self.endpoint, move |mut req: ServiceRequest, srv| { if let Some(ref data) = resource_data { req.add_data_container(Rc::clone(data)); } let fut = srv.call(req); async { Ok(fut.await?.map_into_boxed_body()) } }); config.register_service(rdef, guards, endpoint, None) } } pub struct ResourceFactory { routes: Vec<Route>, default: BoxedHttpServiceFactory, } impl ServiceFactory<ServiceRequest> for ResourceFactory { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = ResourceService; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { // construct default service factory future. let default_fut = self.default.new_service(()); // construct route service factory futures let factory_fut = join_all(self.routes.iter().map(|route| route.new_service(()))); Box::pin(async move { let default = default_fut.await?; let routes = factory_fut .await .into_iter() .collect::<Result<Vec<_>, _>>()?; Ok(ResourceService { routes, default }) }) } } pub struct ResourceService { routes: Vec<RouteService>, default: BoxedHttpService, } impl Service<ServiceRequest> for ResourceService { type Response = ServiceResponse; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, mut req: ServiceRequest) -> Self::Future { for route in &self.routes { if route.check(&mut req) { return route.call(req); } } self.default.call(req) } } #[doc(hidden)] pub struct ResourceEndpoint { factory: Rc<RefCell<Option<ResourceFactory>>>, } impl ResourceEndpoint { fn new(factory: Rc<RefCell<Option<ResourceFactory>>>) -> Self { ResourceEndpoint { factory } } } impl ServiceFactory<ServiceRequest> for ResourceEndpoint { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = ResourceService; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { self.factory.borrow().as_ref().unwrap().new_service(()) } } #[cfg(test)] mod tests { use std::time::Duration; use actix_rt::time::sleep; use actix_utils::future::ok; use super::*; use crate::{ http::{header::HeaderValue, Method, StatusCode}, middleware::DefaultHeaders, test::{call_service, init_service, TestRequest}, App, HttpMessage, }; #[test] fn can_be_returned_from_fn() { fn my_resource_1() -> Resource { web::resource("/test1").route(web::get().to(|| async { "hello" })) } fn my_resource_2() -> Resource< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<impl MessageBody>, Error = Error, InitError = (), >, > { web::resource("/test2") .wrap_fn(|req, srv| { let fut = srv.call(req); async { Ok(fut.await?.map_into_right_body::<()>()) } }) .route(web::get().to(|| async { "hello" })) } fn my_resource_3() -> impl HttpServiceFactory { web::resource("/test3").route(web::get().to(|| async { "hello" })) } App::new() .service(my_resource_1()) .service(my_resource_2()) .service(my_resource_3()); } #[actix_rt::test] async fn test_middleware() { let srv = init_service( App::new().service( web::resource("/test") .name("test") .wrap( DefaultHeaders::new() .add((header::CONTENT_TYPE, HeaderValue::from_static("0001"))), ) .route(web::get().to(HttpResponse::Ok)), ), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), HeaderValue::from_static("0001") ); } #[actix_rt::test] async fn test_middleware_fn() { let srv = init_service( App::new().service( web::resource("/test") .wrap_fn(|req, srv| { let fut = srv.call(req); async { fut.await.map(|mut res| { res.headers_mut() .insert(header::CONTENT_TYPE, HeaderValue::from_static("0001")); res }) } }) .route(web::get().to(HttpResponse::Ok)), ), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), HeaderValue::from_static("0001") ); } #[actix_rt::test] async fn test_to() { let srv = init_service(App::new().service(web::resource("/test").to(|| async { sleep(Duration::from_millis(100)).await; Ok::<_, Error>(HttpResponse::Ok()) }))) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_pattern() { let srv = init_service(App::new().service( web::resource(["/test", "/test2"]).to(|| async { Ok::<_, Error>(HttpResponse::Ok()) }), )) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/test2").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_default_resource() { let srv = init_service( App::new() .service( web::resource("/test") .route(web::get().to(HttpResponse::Ok)) .route(web::delete().to(HttpResponse::Ok)), ) .default_service(|r: ServiceRequest| { ok(r.into_response(HttpResponse::BadRequest())) }), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/test") .method(Method::POST) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); assert_eq!( resp.headers().get(header::ALLOW).unwrap().as_bytes(), b"GET, DELETE" ); let srv = init_service( App::new().service( web::resource("/test") .route(web::get().to(HttpResponse::Ok)) .default_service(|r: ServiceRequest| { ok(r.into_response(HttpResponse::BadRequest())) }), ), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/test") .method(Method::POST) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } #[actix_rt::test] async fn test_resource_guards() { let srv = init_service( App::new() .service( web::resource("/test/{p}") .guard(guard::Get()) .to(HttpResponse::Ok), ) .service( web::resource("/test/{p}") .guard(guard::Put()) .to(HttpResponse::Created), ) .service( web::resource("/test/{p}") .guard(guard::Delete()) .to(HttpResponse::NoContent), ), ) .await; let req = TestRequest::with_uri("/test/it") .method(Method::GET) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/test/it") .method(Method::PUT) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::CREATED); let req = TestRequest::with_uri("/test/it") .method(Method::DELETE) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::NO_CONTENT); } // allow deprecated `{App, Resource}::data` #[allow(deprecated)] #[actix_rt::test] async fn test_data() { let srv = init_service( App::new() .data(1.0f64) .data(1usize) .app_data(web::Data::new('-')) .service( web::resource("/test") .data(10usize) .app_data(web::Data::new('*')) .guard(guard::Get()) .to( |data1: web::Data<usize>, data2: web::Data<char>, data3: web::Data<f64>| { assert_eq!(**data1, 10); assert_eq!(**data2, '*'); let error = f64::EPSILON; assert!((**data3 - 1.0).abs() < error); HttpResponse::Ok() }, ), ), ) .await; let req = TestRequest::get().uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } // allow deprecated `{App, Resource}::data` #[allow(deprecated)] #[actix_rt::test] async fn test_data_default_service() { let srv = init_service( App::new().data(1usize).service( web::resource("/test") .data(10usize) .default_service(web::to(|data: web::Data<usize>| { assert_eq!(**data, 10); HttpResponse::Ok() })), ), ) .await; let req = TestRequest::get().uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_middleware_app_data() { let srv = init_service( App::new().service( web::resource("test") .app_data(1usize) .wrap_fn(|req, srv| { assert_eq!(req.app_data::<usize>(), Some(&1usize)); req.extensions_mut().insert(1usize); srv.call(req) }) .route(web::get().to(HttpResponse::Ok)) .default_service(|req: ServiceRequest| async move { let (req, _) = req.into_parts(); assert_eq!(req.extensions().get::<usize>(), Some(&1)); Ok(ServiceResponse::new( req, HttpResponse::BadRequest().finish(), )) }), ), ) .await; let req = TestRequest::get().uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::post().uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } #[actix_rt::test] async fn test_middleware_body_type() { let srv = init_service( App::new().service( web::resource("/test") .wrap_fn(|req, srv| { let fut = srv.call(req); async { Ok(fut.await?.map_into_right_body::<()>()) } }) .route(web::get().to(|| async { "hello" })), ), ) .await; // test if `try_into_bytes()` is preserved across scope layer use actix_http::body::MessageBody as _; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; let body = resp.into_body(); assert_eq!(body.try_into_bytes().unwrap(), b"hello".as_ref()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/request_data.rs
actix-web/src/request_data.rs
use std::{any::type_name, ops::Deref}; use actix_utils::future::{err, ok, Ready}; use crate::{ dev::Payload, error::ErrorInternalServerError, Error, FromRequest, HttpMessage as _, HttpRequest, }; /// Request-local data extractor. /// /// Request-local data is arbitrary data attached to an individual request, usually /// by middleware. It can be set via `extensions_mut` on [`HttpRequest`][htr_ext_mut] /// or [`ServiceRequest`][srv_ext_mut]. /// /// Unlike app data, request data is dropped when the request has finished processing. This makes it /// useful as a kind of messaging system between middleware and request handlers. It uses the same /// types-as-keys storage system as app data. /// /// # Mutating Request Data /// Note that since extractors must output owned data, only types that `impl Clone` can use this /// extractor. A clone is taken of the required request data and can, therefore, not be directly /// mutated in-place. To mutate request data, continue to use [`HttpRequest::extensions_mut`] or /// re-insert the cloned data back into the extensions map. A `DerefMut` impl is intentionally not /// provided to make this potential foot-gun more obvious. /// /// # Examples /// ```no_run /// # use actix_web::{web, HttpResponse, HttpRequest, Responder, HttpMessage as _}; /// #[derive(Debug, Clone, PartialEq)] /// struct FlagFromMiddleware(String); /// /// /// Use the `ReqData<T>` extractor to access request data in a handler. /// async fn handler( /// req: HttpRequest, /// opt_flag: Option<web::ReqData<FlagFromMiddleware>>, /// ) -> impl Responder { /// // use an option extractor if middleware is not guaranteed to add this type of req data /// if let Some(flag) = opt_flag { /// assert_eq!(&flag.into_inner(), req.extensions().get::<FlagFromMiddleware>().unwrap()); /// } /// /// HttpResponse::Ok() /// } /// ``` /// /// [htr_ext_mut]: crate::HttpRequest::extensions_mut /// [srv_ext_mut]: crate::dev::ServiceRequest::extensions_mut #[derive(Debug, Clone)] pub struct ReqData<T: Clone + 'static>(T); impl<T: Clone + 'static> ReqData<T> { /// Consumes the `ReqData`, returning its wrapped data. pub fn into_inner(self) -> T { self.0 } } impl<T: Clone + 'static> Deref for ReqData<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T: Clone + 'static> FromRequest for ReqData<T> { type Error = Error; type Future = Ready<Result<Self, Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { if let Some(st) = req.extensions().get::<T>() { ok(ReqData(st.clone())) } else { log::debug!( "Failed to construct App-level ReqData extractor. \ Request path: {:?} (type: {})", req.path(), type_name::<T>(), ); err(ErrorInternalServerError( "Missing expected request extension data", )) } } } #[cfg(test)] mod tests { use std::{cell::RefCell, rc::Rc}; use futures_util::TryFutureExt as _; use super::*; use crate::{ dev::Service, http::{Method, StatusCode}, test::{init_service, TestRequest}, web, App, HttpMessage, HttpResponse, }; #[actix_rt::test] async fn req_data_extractor() { let srv = init_service( App::new() .wrap_fn(|req, srv| { if req.method() == Method::POST { req.extensions_mut().insert(42u32); } srv.call(req) }) .service(web::resource("/test").to( |req: HttpRequest, data: Option<ReqData<u32>>| { if req.method() != Method::POST { assert!(data.is_none()); } if let Some(data) = data { assert_eq!(*data, 42); assert_eq!( Some(data.into_inner()), req.extensions().get::<u32>().copied() ); } HttpResponse::Ok() }, )), ) .await; let req = TestRequest::get().uri("/test").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::post().uri("/test").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn req_data_internal_mutability() { let srv = init_service( App::new() .wrap_fn(|req, srv| { let data_before = Rc::new(RefCell::new(42u32)); req.extensions_mut().insert(data_before); srv.call(req).map_ok(|res| { { let ext = res.request().extensions(); let data_after = ext.get::<Rc<RefCell<u32>>>().unwrap(); assert_eq!(*data_after.borrow(), 53u32); } res }) }) .default_service(web::to(|data: ReqData<Rc<RefCell<u32>>>| { assert_eq!(*data.borrow(), 42); *data.borrow_mut() += 11; assert_eq!(*data.borrow(), 53); HttpResponse::Ok() })), ) .await; let req = TestRequest::get().uri("/test").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/lib.rs
actix-web/src/lib.rs
//! Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust. //! //! # Examples //! ```no_run //! use actix_web::{get, web, App, HttpServer, Responder}; //! //! #[get("/hello/{name}")] //! async fn greet(name: web::Path<String>) -> impl Responder { //! format!("Hello {}!", name) //! } //! //! #[actix_web::main] // or #[tokio::main] //! async fn main() -> std::io::Result<()> { //! HttpServer::new(|| { //! App::new().service(greet) //! }) //! .bind(("127.0.0.1", 8080))? //! .run() //! .await //! } //! ``` //! //! # Documentation & Community Resources //! In addition to this API documentation, several other resources are available: //! //! * [Website & User Guide](https://actix.rs/) //! * [Examples Repository](https://github.com/actix/examples) //! * [Community Chat on Discord](https://discord.gg/NWpN5mmg3x) //! //! To get started navigating the API docs, you may consider looking at the following pages first: //! //! * [`App`]: This struct represents an Actix Web application and is used to //! configure routes and other common application settings. //! //! * [`HttpServer`]: This struct represents an HTTP server instance and is //! used to instantiate and configure servers. //! //! * [`web`]: This module provides essential types for route registration as well as //! common utilities for request handlers. //! //! * [`HttpRequest`] and [`HttpResponse`]: These //! structs represent HTTP requests and responses and expose methods for creating, inspecting, //! and otherwise utilizing them. //! //! # Features //! - Supports HTTP/1.x and HTTP/2 //! - Streaming and pipelining //! - Powerful [request routing](https://actix.rs/docs/url-dispatch/) with optional macros //! - Full [Tokio](https://tokio.rs) compatibility //! - Keep-alive and slow requests handling //! - Client/server [WebSockets](https://actix.rs/docs/websockets/) support //! - Transparent content compression/decompression (br, gzip, deflate, zstd) //! - Multipart streams //! - Static assets //! - SSL support using OpenSSL or Rustls //! - Middlewares ([Logger, Session, CORS, etc](middleware)) //! - Integrates with the [`awc` HTTP client](https://docs.rs/awc/) //! - Runs on stable Rust 1.54+ //! //! # Crate Features //! - `cookies` - cookies support (enabled by default) //! - `macros` - routing and runtime macros (enabled by default) //! - `compress-brotli` - brotli content encoding compression support (enabled by default) //! - `compress-gzip` - gzip and deflate content encoding compression support (enabled by default) //! - `compress-zstd` - zstd content encoding compression support (enabled by default) //! - `openssl` - HTTPS support via `openssl` crate, supports `HTTP/2` //! - `rustls` - HTTPS support via `rustls` 0.20 crate, supports `HTTP/2` //! - `rustls-0_21` - HTTPS support via `rustls` 0.21 crate, supports `HTTP/2` //! - `rustls-0_22` - HTTPS support via `rustls` 0.22 crate, supports `HTTP/2` //! - `rustls-0_23` - HTTPS support via `rustls` 0.23 crate, supports `HTTP/2` //! - `secure-cookies` - secure cookies support #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_cfg))] pub use actix_http::{body, HttpMessage}; #[cfg(feature = "cookies")] #[doc(inline)] pub use cookie; pub use mime; mod app; mod app_service; mod config; mod data; pub mod dev; pub mod error; mod extract; pub mod guard; mod handler; mod helpers; pub mod http; mod info; pub mod middleware; mod redirect; mod request; mod request_data; mod resource; mod response; mod rmap; mod route; pub mod rt; mod scope; mod server; mod service; pub mod test; mod thin_data; pub(crate) mod types; pub mod web; #[doc(inline)] pub use crate::error::Result; pub use crate::{ app::App, error::{Error, ResponseError}, extract::FromRequest, handler::Handler, request::HttpRequest, resource::Resource, response::{CustomizeResponder, HttpResponse, HttpResponseBuilder, Responder}, route::Route, scope::Scope, server::HttpServer, types::Either, }; macro_rules! codegen_reexport { ($name:ident) => { #[cfg(feature = "macros")] pub use actix_web_codegen::$name; }; } codegen_reexport!(main); codegen_reexport!(test); codegen_reexport!(route); codegen_reexport!(routes); codegen_reexport!(head); codegen_reexport!(get); codegen_reexport!(post); codegen_reexport!(patch); codegen_reexport!(put); codegen_reexport!(delete); codegen_reexport!(trace); codegen_reexport!(connect); codegen_reexport!(options); codegen_reexport!(scope); pub(crate) type BoxError = Box<dyn std::error::Error>;
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/thin_data.rs
actix-web/src/thin_data.rs
use std::any::type_name; use actix_utils::future::{ready, Ready}; use crate::{dev::Payload, error, FromRequest, HttpRequest}; /// Application data wrapper and extractor for cheaply-cloned types. /// /// Similar to the [`Data`] wrapper but for `Clone`/`Copy` types that are already an `Arc` internally, /// share state using some other means when cloned, or is otherwise static data that is very cheap /// to clone. /// /// Unlike `Data`, this wrapper clones `T` during extraction. Therefore, it is the user's /// responsibility to ensure that clones of `T` do actually share the same state, otherwise state /// may be unexpectedly different across multiple requests. /// /// Note that if your type is literally an `Arc<T>` then it's recommended to use the /// [`Data::from(arc)`][data_from_arc] conversion instead. /// /// # Examples /// /// ``` /// use actix_web::{ /// web::{self, ThinData}, /// App, HttpResponse, Responder, /// }; /// /// // Use the `ThinData<T>` extractor to access a database connection pool. /// async fn index(ThinData(db_pool): ThinData<DbPool>) -> impl Responder { /// // database action ... /// /// HttpResponse::Ok() /// } /// /// # type DbPool = (); /// let db_pool = DbPool::default(); /// /// App::new() /// .app_data(ThinData(db_pool.clone())) /// .service(web::resource("/").get(index)) /// # ; /// ``` /// /// [`Data`]: crate::web::Data /// [data_from_arc]: crate::web::Data#impl-From<Arc<T>>-for-Data<T> #[derive(Debug, Clone)] pub struct ThinData<T>(pub T); impl_more::impl_as_ref!(ThinData<T> => T); impl_more::impl_as_mut!(ThinData<T> => T); impl_more::impl_deref_and_mut!(<T> in ThinData<T> => T); impl<T: Clone + 'static> FromRequest for ThinData<T> { type Error = crate::Error; type Future = Ready<Result<Self, Self::Error>>; #[inline] fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ready(req.app_data::<Self>().cloned().ok_or_else(|| { log::debug!( "Failed to extract `ThinData<{}>` for `{}` handler. For the ThinData extractor to work \ correctly, wrap the data with `ThinData()` and pass it to `App::app_data()`. \ Ensure that types align in both the set and retrieve calls.", type_name::<T>(), req.match_name().unwrap_or(req.path()) ); error::ErrorInternalServerError( "Requested application data is not configured correctly. \ View/enable debug logs for more details.", ) })) } } #[cfg(test)] mod tests { use std::sync::{Arc, Mutex}; use super::*; use crate::{ http::StatusCode, test::{call_service, init_service, TestRequest}, web, App, HttpResponse, }; type TestT = Arc<Mutex<u32>>; #[actix_rt::test] async fn thin_data() { let test_data = TestT::default(); let app = init_service(App::new().app_data(ThinData(test_data.clone())).service( web::resource("/").to(|td: ThinData<TestT>| { *td.lock().unwrap() += 1; HttpResponse::Ok() }), )) .await; for _ in 0..3 { let req = TestRequest::default().to_request(); let resp = call_service(&app, req).await; assert_eq!(resp.status(), StatusCode::OK); } assert_eq!(*test_data.lock().unwrap(), 3); } #[actix_rt::test] async fn thin_data_missing() { let app = init_service( App::new().service(web::resource("/").to(|_: ThinData<u32>| HttpResponse::Ok())), ) .await; let req = TestRequest::default().to_request(); let resp = call_service(&app, req).await; assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/helpers.rs
actix-web/src/helpers.rs
use std::io; use bytes::BufMut; /// An `io::Write`r that only requires mutable reference and assumes that there is space available /// in the buffer for every write operation or that it can be extended implicitly (like /// `bytes::BytesMut`, for example). /// /// This is slightly faster (~10%) than `bytes::buf::Writer` in such cases because it does not /// perform a remaining length check before writing. pub(crate) struct MutWriter<'a, B>(pub(crate) &'a mut B); impl<B> io::Write for MutWriter<'_, B> where B: BufMut, { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.put_slice(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/redirect.rs
actix-web/src/redirect.rs
//! See [`Redirect`] for service/responder documentation. use std::borrow::Cow; use actix_utils::future::ready; use crate::{ dev::{fn_service, AppService, HttpServiceFactory, ResourceDef, ServiceRequest}, http::{header::LOCATION, StatusCode}, HttpRequest, HttpResponse, Responder, }; /// An HTTP service for redirecting one path to another path or URL. /// /// By default, the "307 Temporary Redirect" status is used when responding. See [this MDN /// article][mdn-redirects] on why 307 is preferred over 302. /// /// # Examples /// As service: /// ``` /// use actix_web::{web, App}; /// /// App::new() /// // redirect "/duck" to DuckDuckGo /// .service(web::redirect("/duck", "https://duck.com")) /// .service( /// // redirect "/api/old" to "/api/new" /// web::scope("/api").service(web::redirect("/old", "/new")) /// ); /// ``` /// /// As responder: /// ``` /// use actix_web::{web::Redirect, Responder}; /// /// async fn handler() -> impl Responder { /// // sends a permanent (308) redirect to duck.com /// Redirect::to("https://duck.com").permanent() /// } /// # actix_web::web::to(handler); /// ``` /// /// [mdn-redirects]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections#temporary_redirections #[derive(Debug, Clone)] pub struct Redirect { from: Cow<'static, str>, to: Cow<'static, str>, status_code: StatusCode, } impl Redirect { /// Construct a new `Redirect` service that matches a path. /// /// This service will match exact paths equal to `from` within the current scope. I.e., when /// registered on the root `App`, it will match exact, whole paths. But when registered on a /// `Scope`, it will match paths under that scope, ignoring the defined scope prefix, just like /// a normal `Resource` or `Route`. /// /// The `to` argument can be path or URL; whatever is provided shall be used verbatim when /// setting the redirect location. This means that relative paths can be used to navigate /// relatively to matched paths. /// /// Prefer [`Redirect::to()`](Self::to) when using `Redirect` as a responder since `from` has /// no meaning in that context. /// /// # Examples /// ``` /// # use actix_web::{web::Redirect, App}; /// App::new() /// // redirects "/oh/hi/mark" to "/oh/bye/johnny" /// .service(Redirect::new("/oh/hi/mark", "../../bye/johnny")); /// ``` pub fn new(from: impl Into<Cow<'static, str>>, to: impl Into<Cow<'static, str>>) -> Self { Self { from: from.into(), to: to.into(), status_code: StatusCode::TEMPORARY_REDIRECT, } } /// Construct a new `Redirect` to use as a responder. /// /// Only receives the `to` argument since responders do not need to do route matching. /// /// # Examples /// ``` /// use actix_web::{web::Redirect, Responder}; /// /// async fn admin_page() -> impl Responder { /// // sends a temporary 307 redirect to the login path /// Redirect::to("/login") /// } /// # actix_web::web::to(admin_page); /// ``` pub fn to(to: impl Into<Cow<'static, str>>) -> Self { Self { from: "/".into(), to: to.into(), status_code: StatusCode::TEMPORARY_REDIRECT, } } /// Use the "308 Permanent Redirect" status when responding. /// /// See [this MDN article][mdn-redirects] on why 308 is preferred over 301. /// /// [mdn-redirects]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections#permanent_redirections pub fn permanent(self) -> Self { self.using_status_code(StatusCode::PERMANENT_REDIRECT) } /// Use the "307 Temporary Redirect" status when responding. /// /// See [this MDN article][mdn-redirects] on why 307 is preferred over 302. /// /// [mdn-redirects]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections#temporary_redirections pub fn temporary(self) -> Self { self.using_status_code(StatusCode::TEMPORARY_REDIRECT) } /// Use the "303 See Other" status when responding. /// /// This status code is semantically correct as the response to a successful login, for example. pub fn see_other(self) -> Self { self.using_status_code(StatusCode::SEE_OTHER) } /// Allows the use of custom status codes for less common redirect types. /// /// In most cases, the default status ("308 Permanent Redirect") or using the `temporary` /// method, which uses the "307 Temporary Redirect" status have more consistent behavior than /// 301 and 302 codes, respectively. /// /// ``` /// # use actix_web::{http::StatusCode, web::Redirect}; /// // redirects would use "301 Moved Permanently" status code /// Redirect::new("/old", "/new") /// .using_status_code(StatusCode::MOVED_PERMANENTLY); /// /// // redirects would use "302 Found" status code /// Redirect::new("/old", "/new") /// .using_status_code(StatusCode::FOUND); /// ``` pub fn using_status_code(mut self, status: StatusCode) -> Self { self.status_code = status; self } } impl HttpServiceFactory for Redirect { fn register(self, config: &mut AppService) { let redirect = self.clone(); let rdef = ResourceDef::new(self.from.into_owned()); let redirect_factory = fn_service(move |mut req: ServiceRequest| { let res = redirect.clone().respond_to(req.parts_mut().0); ready(Ok(req.into_response(res.map_into_boxed_body()))) }); config.register_service(rdef, None, redirect_factory, None) } } impl Responder for Redirect { type Body = (); fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> { let mut res = HttpResponse::with_body(self.status_code, ()); if let Ok(hdr_val) = self.to.parse() { res.headers_mut().insert(LOCATION, hdr_val); } else { log::error!( "redirect target location can not be converted to header value: {:?}", self.to, ); } res } } #[cfg(test)] mod tests { use super::*; use crate::{dev::Service, test, App}; #[actix_rt::test] async fn absolute_redirects() { let redirector = Redirect::new("/one", "/two").permanent(); let svc = test::init_service(App::new().service(redirector)).await; let req = test::TestRequest::default().uri("/one").to_request(); let res = svc.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::from_u16(308).unwrap()); let hdr = res.headers().get(&LOCATION).unwrap(); assert_eq!(hdr.to_str().unwrap(), "/two"); } #[actix_rt::test] async fn relative_redirects() { let redirector = Redirect::new("/one", "two").permanent(); let svc = test::init_service(App::new().service(redirector)).await; let req = test::TestRequest::default().uri("/one").to_request(); let res = svc.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::from_u16(308).unwrap()); let hdr = res.headers().get(&LOCATION).unwrap(); assert_eq!(hdr.to_str().unwrap(), "two"); } #[actix_rt::test] async fn temporary_redirects() { let external_service = Redirect::new("/external", "https://duck.com"); let svc = test::init_service(App::new().service(external_service)).await; let req = test::TestRequest::default().uri("/external").to_request(); let res = svc.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::from_u16(307).unwrap()); let hdr = res.headers().get(&LOCATION).unwrap(); assert_eq!(hdr.to_str().unwrap(), "https://duck.com"); } #[actix_rt::test] async fn as_responder() { let responder = Redirect::to("https://duck.com"); let req = test::TestRequest::default().to_http_request(); let res = responder.respond_to(&req); assert_eq!(res.status(), StatusCode::from_u16(307).unwrap()); let hdr = res.headers().get(&LOCATION).unwrap(); assert_eq!(hdr.to_str().unwrap(), "https://duck.com"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/info.rs
actix-web/src/info.rs
use std::{convert::Infallible, net::SocketAddr}; use actix_utils::future::{err, ok, Ready}; use derive_more::{Display, Error}; use crate::{ dev::{AppConfig, Payload, RequestHead}, http::{ header::{self, HeaderName}, uri::{Authority, Scheme}, }, FromRequest, HttpRequest, ResponseError, }; static X_FORWARDED_FOR: HeaderName = HeaderName::from_static("x-forwarded-for"); static X_FORWARDED_HOST: HeaderName = HeaderName::from_static("x-forwarded-host"); static X_FORWARDED_PROTO: HeaderName = HeaderName::from_static("x-forwarded-proto"); /// Trim whitespace then any quote marks. fn unquote(val: &str) -> &str { val.trim().trim_start_matches('"').trim_end_matches('"') } /// Remove port and IPv6 square brackets from a peer specification. fn bare_address(val: &str) -> &str { if val.starts_with('[') { val.split("]:") .next() .map(|s| s.trim_start_matches('[').trim_end_matches(']')) // this indicates that the IPv6 address is malformed so shouldn't // usually happen, but if it does, just return the original input .unwrap_or(val) } else { val.split(':').next().unwrap_or(val) } } /// Extracts and trims first value for given header name. fn first_header_value<'a>(req: &'a RequestHead, name: &'_ HeaderName) -> Option<&'a str> { let hdr = req.headers.get(name)?.to_str().ok()?; let val = hdr.split(',').next()?.trim(); Some(val) } /// HTTP connection information. /// /// `ConnectionInfo` implements `FromRequest` and can be extracted in handlers. /// /// # Examples /// ``` /// # use actix_web::{HttpResponse, Responder}; /// use actix_web::dev::ConnectionInfo; /// /// async fn handler(conn: ConnectionInfo) -> impl Responder { /// match conn.host() { /// "actix.rs" => HttpResponse::Ok().body("Welcome!"), /// "admin.actix.rs" => HttpResponse::Ok().body("Admin portal."), /// _ => HttpResponse::NotFound().finish() /// } /// } /// # let _svc = actix_web::web::to(handler); /// ``` /// /// # Implementation Notes /// Parses `Forwarded` header information according to [RFC 7239][rfc7239] but does not try to /// interpret the values for each property. As such, the getter methods on `ConnectionInfo` return /// strings instead of IP addresses or other types to acknowledge that they may be /// [obfuscated][rfc7239-63] or [unknown][rfc7239-62]. /// /// If the older, related headers are also present (eg. `X-Forwarded-For`), then `Forwarded` /// is preferred. /// /// [rfc7239]: https://datatracker.ietf.org/doc/html/rfc7239 /// [rfc7239-62]: https://datatracker.ietf.org/doc/html/rfc7239#section-6.2 /// [rfc7239-63]: https://datatracker.ietf.org/doc/html/rfc7239#section-6.3 #[derive(Debug, Clone, Default)] pub struct ConnectionInfo { host: String, scheme: String, peer_addr: Option<String>, realip_remote_addr: Option<String>, } impl ConnectionInfo { pub(crate) fn new(req: &RequestHead, cfg: &AppConfig) -> ConnectionInfo { let mut host = None; let mut scheme = None; let mut realip_remote_addr = None; for (name, val) in req .headers .get_all(&header::FORWARDED) .filter_map(|hdr| hdr.to_str().ok()) // "for=1.2.3.4, for=5.6.7.8; scheme=https" .flat_map(|val| val.split(';')) // ["for=1.2.3.4, for=5.6.7.8", " scheme=https"] .flat_map(|vals| vals.split(',')) // ["for=1.2.3.4", " for=5.6.7.8", " scheme=https"] .flat_map(|pair| { let mut items = pair.trim().splitn(2, '='); Some((items.next()?, items.next()?)) }) { // [(name , val ), ... ] // [("for", "1.2.3.4"), ("for", "5.6.7.8"), ("scheme", "https")] // taking the first value for each property is correct because spec states that first // "for" value is client and rest are proxies; multiple values other properties have // no defined semantics // // > In a chain of proxy servers where this is fully utilized, the first // > "for" parameter will disclose the client where the request was first // > made, followed by any subsequent proxy identifiers. // --- https://datatracker.ietf.org/doc/html/rfc7239#section-5.2 match name.trim().to_lowercase().as_str() { "for" => realip_remote_addr.get_or_insert_with(|| bare_address(unquote(val))), "proto" => scheme.get_or_insert_with(|| unquote(val)), "host" => host.get_or_insert_with(|| unquote(val)), "by" => { // TODO: implement https://datatracker.ietf.org/doc/html/rfc7239#section-5.1 continue; } _ => continue, }; } let scheme = scheme .or_else(|| first_header_value(req, &X_FORWARDED_PROTO)) .or_else(|| req.uri.scheme().map(Scheme::as_str)) .or_else(|| Some("https").filter(|_| cfg.secure())) .unwrap_or("http") .to_owned(); let host = host .or_else(|| first_header_value(req, &X_FORWARDED_HOST)) .or_else(|| req.headers.get(&header::HOST)?.to_str().ok()) .or_else(|| req.uri.authority().map(Authority::as_str)) .unwrap_or_else(|| cfg.host()) .to_owned(); let realip_remote_addr = realip_remote_addr .or_else(|| first_header_value(req, &X_FORWARDED_FOR)) .map(str::to_owned); let peer_addr = req.peer_addr.map(|addr| addr.ip().to_string()); ConnectionInfo { host, scheme, peer_addr, realip_remote_addr, } } /// Real IP (remote address) of client that initiated request. /// /// The address is resolved through the following, in order: /// - `Forwarded` header /// - `X-Forwarded-For` header /// - peer address of opened socket (same as [`peer_addr`](Self::peer_addr)) /// /// # Security /// Do not use this function for security purposes unless you can be sure that the `Forwarded` /// and `X-Forwarded-For` headers cannot be spoofed by the client. If you are running without a /// proxy then [obtaining the peer address](Self::peer_addr) would be more appropriate. #[inline] pub fn realip_remote_addr(&self) -> Option<&str> { self.realip_remote_addr .as_deref() .or(self.peer_addr.as_deref()) } /// Returns serialized IP address of the peer connection. /// /// See [`HttpRequest::peer_addr`] for more details. #[inline] pub fn peer_addr(&self) -> Option<&str> { self.peer_addr.as_deref() } /// Hostname of the request. /// /// Hostname is resolved through the following, in order: /// - `Forwarded` header /// - `X-Forwarded-Host` header /// - `Host` header /// - request target / URI /// - configured server hostname #[inline] pub fn host(&self) -> &str { &self.host } /// Scheme of the request. /// /// Scheme is resolved through the following, in order: /// - `Forwarded` header /// - `X-Forwarded-Proto` header /// - request target / URI #[inline] pub fn scheme(&self) -> &str { &self.scheme } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `peer_addr`.")] pub fn remote_addr(&self) -> Option<&str> { self.peer_addr() } } impl FromRequest for ConnectionInfo { type Error = Infallible; type Future = Ready<Result<Self, Self::Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ok(req.connection_info().clone()) } } /// Extractor for peer's socket address. /// /// Also see [`HttpRequest::peer_addr`] and [`ConnectionInfo::peer_addr`]. /// /// # Examples /// ``` /// # use actix_web::Responder; /// use actix_web::dev::PeerAddr; /// /// async fn handler(peer_addr: PeerAddr) -> impl Responder { /// let socket_addr = peer_addr.0; /// socket_addr.to_string() /// } /// # let _svc = actix_web::web::to(handler); /// ``` #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Display)] #[display("{}", _0)] pub struct PeerAddr(pub SocketAddr); impl PeerAddr { /// Unwrap into inner `SocketAddr` value. pub fn into_inner(self) -> SocketAddr { self.0 } } #[derive(Debug, Display, Error)] #[non_exhaustive] #[display("Missing peer address")] pub struct MissingPeerAddr; impl ResponseError for MissingPeerAddr {} impl FromRequest for PeerAddr { type Error = MissingPeerAddr; type Future = Ready<Result<Self, Self::Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { match req.peer_addr() { Some(addr) => ok(PeerAddr(addr)), None => { log::error!("Missing peer address."); err(MissingPeerAddr) } } } } #[cfg(test)] mod tests { use super::*; use crate::test::TestRequest; const X_FORWARDED_FOR: &str = "x-forwarded-for"; const X_FORWARDED_HOST: &str = "x-forwarded-host"; const X_FORWARDED_PROTO: &str = "x-forwarded-proto"; #[test] fn info_default() { let req = TestRequest::default().to_http_request(); let info = req.connection_info(); assert_eq!(info.scheme(), "http"); assert_eq!(info.host(), "localhost:8080"); } #[test] fn host_header() { let req = TestRequest::default() .insert_header((header::HOST, "rust-lang.org")) .to_http_request(); let info = req.connection_info(); assert_eq!(info.scheme(), "http"); assert_eq!(info.host(), "rust-lang.org"); assert_eq!(info.realip_remote_addr(), None); } #[test] fn x_forwarded_for_header() { let req = TestRequest::default() .insert_header((X_FORWARDED_FOR, "192.0.2.60")) .to_http_request(); let info = req.connection_info(); assert_eq!(info.realip_remote_addr(), Some("192.0.2.60")); } #[test] fn x_forwarded_host_header() { let req = TestRequest::default() .insert_header((X_FORWARDED_HOST, "192.0.2.60")) .to_http_request(); let info = req.connection_info(); assert_eq!(info.host(), "192.0.2.60"); assert_eq!(info.realip_remote_addr(), None); } #[test] fn x_forwarded_proto_header() { let req = TestRequest::default() .insert_header((X_FORWARDED_PROTO, "https")) .to_http_request(); let info = req.connection_info(); assert_eq!(info.scheme(), "https"); } #[test] fn forwarded_header() { let req = TestRequest::default() .insert_header(( header::FORWARDED, "for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org", )) .to_http_request(); let info = req.connection_info(); assert_eq!(info.scheme(), "https"); assert_eq!(info.host(), "rust-lang.org"); assert_eq!(info.realip_remote_addr(), Some("192.0.2.60")); let req = TestRequest::default() .insert_header(( header::FORWARDED, "for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org", )) .to_http_request(); let info = req.connection_info(); assert_eq!(info.scheme(), "https"); assert_eq!(info.host(), "rust-lang.org"); assert_eq!(info.realip_remote_addr(), Some("192.0.2.60")); } #[test] fn forwarded_case_sensitivity() { let req = TestRequest::default() .insert_header((header::FORWARDED, "For=192.0.2.60")) .to_http_request(); let info = req.connection_info(); assert_eq!(info.realip_remote_addr(), Some("192.0.2.60")); } #[test] fn forwarded_weird_whitespace() { let req = TestRequest::default() .insert_header((header::FORWARDED, "for= 1.2.3.4; proto= https")) .to_http_request(); let info = req.connection_info(); assert_eq!(info.realip_remote_addr(), Some("1.2.3.4")); assert_eq!(info.scheme(), "https"); let req = TestRequest::default() .insert_header((header::FORWARDED, " for = 1.2.3.4 ")) .to_http_request(); let info = req.connection_info(); assert_eq!(info.realip_remote_addr(), Some("1.2.3.4")); } #[test] fn forwarded_for_quoted() { let req = TestRequest::default() .insert_header((header::FORWARDED, r#"for="192.0.2.60:8080""#)) .to_http_request(); let info = req.connection_info(); assert_eq!(info.realip_remote_addr(), Some("192.0.2.60")); } #[test] fn forwarded_for_ipv6() { let req = TestRequest::default() .insert_header((header::FORWARDED, r#"for="[2001:db8:cafe::17]""#)) .to_http_request(); let info = req.connection_info(); assert_eq!(info.realip_remote_addr(), Some("2001:db8:cafe::17")); } #[test] fn forwarded_for_ipv6_with_port() { let req = TestRequest::default() .insert_header((header::FORWARDED, r#"for="[2001:db8:cafe::17]:4711""#)) .to_http_request(); let info = req.connection_info(); assert_eq!(info.realip_remote_addr(), Some("2001:db8:cafe::17")); } #[test] fn forwarded_for_multiple() { let req = TestRequest::default() .insert_header((header::FORWARDED, "for=192.0.2.60, for=198.51.100.17")) .to_http_request(); let info = req.connection_info(); // takes the first value assert_eq!(info.realip_remote_addr(), Some("192.0.2.60")); } #[test] fn scheme_from_uri() { let req = TestRequest::get() .uri("https://actix.rs/test") .to_http_request(); let info = req.connection_info(); assert_eq!(info.scheme(), "https"); } #[test] fn host_from_uri() { let req = TestRequest::get() .uri("https://actix.rs/test") .to_http_request(); let info = req.connection_info(); assert_eq!(info.host(), "actix.rs"); } #[test] fn host_from_server_hostname() { let mut req = TestRequest::get(); req.set_server_hostname("actix.rs"); let req = req.to_http_request(); let info = req.connection_info(); assert_eq!(info.host(), "actix.rs"); } #[actix_rt::test] async fn conn_info_extract() { let req = TestRequest::default() .uri("https://actix.rs/test") .to_http_request(); let conn_info = ConnectionInfo::extract(&req).await.unwrap(); assert_eq!(conn_info.scheme(), "https"); assert_eq!(conn_info.host(), "actix.rs"); } #[actix_rt::test] async fn peer_addr_extract() { let req = TestRequest::default().to_http_request(); let res = PeerAddr::extract(&req).await; assert!(res.is_err()); let addr = "127.0.0.1:8080".parse().unwrap(); let req = TestRequest::default().peer_addr(addr).to_http_request(); let peer_addr = PeerAddr::extract(&req).await.unwrap(); assert_eq!(peer_addr, PeerAddr(addr)); } #[actix_rt::test] async fn remote_address() { let req = TestRequest::default().to_http_request(); let res = ConnectionInfo::extract(&req).await.unwrap(); assert!(res.peer_addr().is_none()); let addr = "127.0.0.1:8080".parse().unwrap(); let req = TestRequest::default().peer_addr(addr).to_http_request(); let conn_info = ConnectionInfo::extract(&req).await.unwrap(); assert_eq!(conn_info.peer_addr().unwrap(), "127.0.0.1"); } #[actix_rt::test] async fn real_ip_from_socket_addr() { let req = TestRequest::default().to_http_request(); let res = ConnectionInfo::extract(&req).await.unwrap(); assert!(res.realip_remote_addr().is_none()); let addr = "127.0.0.1:8080".parse().unwrap(); let req = TestRequest::default().peer_addr(addr).to_http_request(); let conn_info = ConnectionInfo::extract(&req).await.unwrap(); assert_eq!(conn_info.realip_remote_addr().unwrap(), "127.0.0.1"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/rt.rs
actix-web/src/rt.rs
//! A selection of re-exports from [`tokio`] and [`actix-rt`]. //! //! Actix Web runs on [Tokio], providing full[^compat] compatibility with its huge ecosystem of //! crates. Each of the server's workers uses a single-threaded runtime. Read more about the //! architecture in [`actix-rt`]'s docs. //! //! # Running Actix Web Without Macros //! //! ```no_run //! use actix_web::{middleware, rt, web, App, HttpRequest, HttpServer}; //! //! async fn index(req: HttpRequest) -> &'static str { //! println!("REQ: {:?}", req); //! "Hello world!\r\n" //! } //! //! fn main() -> std::io::Result<()> { //! rt::System::new().block_on( //! HttpServer::new(|| { //! App::new().service(web::resource("/").route(web::get().to(index))) //! }) //! .bind(("127.0.0.1", 8080))? //! .run() //! ) //! } //! ``` //! //! # Running Actix Web Using `#[tokio::main]` //! //! If you need to run something that uses Tokio's work stealing functionality alongside Actix Web, //! you can run Actix Web under `#[tokio::main]`. The [`Server`](crate::dev::Server) object returned //! from [`HttpServer::run`](crate::HttpServer::run) can also be [`spawn`]ed, if preferred. //! //! Note that `actix` actor support (and therefore WebSocket support through `actix-web-actors`) //! still require `#[actix_web::main]` since they require a [`System`] to be set up. //! //! Also note that calls to this module's [`spawn()`] re-export require an `#[actix_web::main]` //! runtime (or a manually configured `LocalSet`) since it makes calls into to the current thread's //! `LocalSet`, which `#[tokio::main]` does not set up. //! //! ```no_run //! use actix_web::{get, middleware, rt, web, App, HttpRequest, HttpServer}; //! //! #[get("/")] //! async fn index(req: HttpRequest) -> &'static str { //! println!("REQ: {:?}", req); //! "Hello world!\r\n" //! } //! //! #[tokio::main] //! async fn main() -> std::io::Result<()> { //! HttpServer::new(|| { //! App::new().service(index) //! }) //! .bind(("127.0.0.1", 8080))? //! .run() //! .await //! } //! ``` //! //! [^compat]: Crates that use Tokio's [`block_in_place`] will not work with Actix Web. Fortunately, //! the vast majority of Tokio-based crates do not use it. //! //! [`actix-rt`]: https://docs.rs/actix-rt //! [`tokio`]: https://docs.rs/tokio //! [Tokio]: https://docs.rs/tokio //! [`spawn`]: https://docs.rs/tokio/1/tokio/fn.spawn.html //! [`block_in_place`]: https://docs.rs/tokio/1/tokio/task/fn.block_in_place.html // In particular: // - Omit the `Arbiter` types because they have limited value here. // - Re-export but hide the runtime macros because they won't work directly but are required for // `#[actix_web::main]` and `#[actix_web::test]` to work. #[cfg(feature = "macros")] #[doc(hidden)] pub use actix_macros::{main, test}; pub use actix_rt::{net, pin, signal, spawn, task, time, Runtime, System, SystemRunner};
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/service.rs
actix-web/src/service.rs
use std::{ cell::{Ref, RefMut}, fmt, net, rc::Rc, }; use actix_http::{ body::{BoxBody, EitherBody, MessageBody}, header::HeaderMap, BoxedPayloadStream, Extensions, HttpMessage, Method, Payload, RequestHead, Response, ResponseHead, StatusCode, Uri, Version, }; use actix_router::{IntoPatterns, Path, Patterns, Resource, ResourceDef, Url}; use actix_service::{ boxed::{BoxService, BoxServiceFactory}, IntoServiceFactory, ServiceFactory, }; #[cfg(feature = "cookies")] use cookie::{Cookie, ParseError as CookieParseError}; use crate::{ config::{AppConfig, AppService}, dev::ensure_leading_slash, guard::{Guard, GuardContext}, info::ConnectionInfo, rmap::ResourceMap, Error, FromRequest, HttpRequest, HttpResponse, }; pub(crate) type BoxedHttpService = BoxService<ServiceRequest, ServiceResponse<BoxBody>, Error>; pub(crate) type BoxedHttpServiceFactory = BoxServiceFactory<(), ServiceRequest, ServiceResponse<BoxBody>, Error, ()>; pub trait HttpServiceFactory { fn register(self, config: &mut AppService); } impl<T: HttpServiceFactory> HttpServiceFactory for Vec<T> { fn register(self, config: &mut AppService) { self.into_iter() .for_each(|factory| factory.register(config)); } } pub(crate) trait AppServiceFactory { fn register(&mut self, config: &mut AppService); } pub(crate) struct ServiceFactoryWrapper<T> { factory: Option<T>, } impl<T> ServiceFactoryWrapper<T> { pub fn new(factory: T) -> Self { Self { factory: Some(factory), } } } impl<T> AppServiceFactory for ServiceFactoryWrapper<T> where T: HttpServiceFactory, { fn register(&mut self, config: &mut AppService) { if let Some(item) = self.factory.take() { item.register(config) } } } /// A service level request wrapper. /// /// Allows mutable access to request's internal structures. pub struct ServiceRequest { req: HttpRequest, payload: Payload, } impl ServiceRequest { /// Construct `ServiceRequest` from parts. pub(crate) fn new(req: HttpRequest, payload: Payload) -> Self { Self { req, payload } } /// Deconstruct `ServiceRequest` into inner parts. #[inline] pub fn into_parts(self) -> (HttpRequest, Payload) { (self.req, self.payload) } /// Returns mutable accessors to inner parts. #[inline] pub fn parts_mut(&mut self) -> (&mut HttpRequest, &mut Payload) { (&mut self.req, &mut self.payload) } /// Returns immutable accessors to inner parts. #[inline] pub fn parts(&self) -> (&HttpRequest, &Payload) { (&self.req, &self.payload) } /// Returns immutable accessor to inner [`HttpRequest`]. #[inline] pub fn request(&self) -> &HttpRequest { &self.req } /// Derives a type from this request using an [extractor](crate::FromRequest). /// /// Returns the `T` extractor's `Future` type which can be `await`ed. This is particularly handy /// when you want to use an extractor in a middleware implementation. /// /// # Examples /// ``` /// use actix_web::{ /// dev::{ServiceRequest, ServiceResponse}, /// web::Path, Error /// }; /// /// async fn my_helper(mut srv_req: ServiceRequest) -> Result<ServiceResponse, Error> { /// let path = srv_req.extract::<Path<(String, u32)>>().await?; /// // [...] /// # todo!() /// } /// ``` pub fn extract<T>(&mut self) -> <T as FromRequest>::Future where T: FromRequest, { T::from_request(&self.req, &mut self.payload) } /// Construct request from parts. pub fn from_parts(req: HttpRequest, payload: Payload) -> Self { #[cfg(debug_assertions)] if Rc::strong_count(&req.inner) > 1 { log::warn!("Cloning an `HttpRequest` might cause panics."); } Self { req, payload } } /// Construct `ServiceRequest` with no payload from given `HttpRequest`. #[inline] pub fn from_request(req: HttpRequest) -> Self { ServiceRequest { req, payload: Payload::None, } } /// Create `ServiceResponse` from this request and given response. #[inline] pub fn into_response<B, R: Into<Response<B>>>(self, res: R) -> ServiceResponse<B> { let res = HttpResponse::from(res.into()); ServiceResponse::new(self.req, res) } /// Create `ServiceResponse` from this request and given error. #[inline] pub fn error_response<E: Into<Error>>(self, err: E) -> ServiceResponse { let res = HttpResponse::from_error(err.into()); ServiceResponse::new(self.req, res) } /// Returns a reference to the request head. #[inline] pub fn head(&self) -> &RequestHead { self.req.head() } /// Returns a mutable reference to the request head. #[inline] pub fn head_mut(&mut self) -> &mut RequestHead { self.req.head_mut() } /// Returns the request URI. #[inline] pub fn uri(&self) -> &Uri { &self.head().uri } /// Returns the request method. #[inline] pub fn method(&self) -> &Method { &self.head().method } /// Returns the request version. #[inline] pub fn version(&self) -> Version { self.head().version } /// Returns a reference to request headers. #[inline] pub fn headers(&self) -> &HeaderMap { &self.head().headers } /// Returns a mutable reference to request headers. #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { &mut self.head_mut().headers } /// Returns request path. #[inline] pub fn path(&self) -> &str { self.head().uri.path() } /// Counterpart to [`HttpRequest::query_string`]. #[inline] pub fn query_string(&self) -> &str { self.req.query_string() } /// Returns peer's socket address. /// /// See [`HttpRequest::peer_addr`] for more details. /// /// [`HttpRequest::peer_addr`]: crate::HttpRequest::peer_addr #[inline] pub fn peer_addr(&self) -> Option<net::SocketAddr> { self.head().peer_addr } /// Returns a reference to connection info. #[inline] pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> { self.req.connection_info() } /// Counterpart to [`HttpRequest::match_info`]. #[inline] pub fn match_info(&self) -> &Path<Url> { self.req.match_info() } /// Returns a mutable reference to the path match information. #[inline] pub fn match_info_mut(&mut self) -> &mut Path<Url> { self.req.match_info_mut() } /// Counterpart to [`HttpRequest::match_name`]. #[inline] pub fn match_name(&self) -> Option<&str> { self.req.match_name() } /// Counterpart to [`HttpRequest::match_pattern`]. #[inline] pub fn match_pattern(&self) -> Option<String> { self.req.match_pattern() } /// Returns a reference to the application's resource map. /// Counterpart to [`HttpRequest::resource_map`]. #[inline] pub fn resource_map(&self) -> &ResourceMap { self.req.resource_map() } /// Counterpart to [`HttpRequest::app_config`]. #[inline] pub fn app_config(&self) -> &AppConfig { self.req.app_config() } /// Counterpart to [`HttpRequest::app_data`]. #[inline] pub fn app_data<T: 'static>(&self) -> Option<&T> { for container in self.req.inner.app_data.iter().rev() { if let Some(data) = container.get::<T>() { return Some(data); } } None } /// Counterpart to [`HttpRequest::conn_data`]. #[inline] pub fn conn_data<T: 'static>(&self) -> Option<&T> { self.req.conn_data() } /// Return request cookies. #[cfg(feature = "cookies")] #[inline] pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> { self.req.cookies() } /// Return request cookie. #[cfg(feature = "cookies")] #[inline] pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> { self.req.cookie(name) } /// Set request payload. #[inline] pub fn set_payload(&mut self, payload: Payload) { self.payload = payload; } /// Add data container to request's resolution set. /// /// In middleware, prefer [`extensions_mut`](ServiceRequest::extensions_mut) for request-local /// data since it is assumed that the same app data is presented for every request. pub fn add_data_container(&mut self, extensions: Rc<Extensions>) { Rc::get_mut(&mut (self.req).inner) .unwrap() .app_data .push(extensions); } /// Creates a context object for use with a routing [guard](crate::guard). #[inline] pub fn guard_ctx(&self) -> GuardContext<'_> { GuardContext { req: self } } } impl Resource for ServiceRequest { type Path = Url; #[inline] fn resource_path(&mut self) -> &mut Path<Self::Path> { self.match_info_mut() } } impl HttpMessage for ServiceRequest { type Stream = BoxedPayloadStream; #[inline] fn headers(&self) -> &HeaderMap { &self.head().headers } #[inline] fn extensions(&self) -> Ref<'_, Extensions> { self.req.extensions() } #[inline] fn extensions_mut(&self) -> RefMut<'_, Extensions> { self.req.extensions_mut() } #[inline] fn take_payload(&mut self) -> Payload<Self::Stream> { self.payload.take() } } impl fmt::Debug for ServiceRequest { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "\nServiceRequest {:?} {}:{}", self.head().version, self.head().method, self.path() )?; if !self.query_string().is_empty() { writeln!(f, " query: ?{:?}", self.query_string())?; } if !self.match_info().is_empty() { writeln!(f, " params: {:?}", self.match_info())?; } writeln!(f, " headers:")?; for (key, val) in self.headers().iter() { writeln!(f, " {:?}: {:?}", key, val)?; } Ok(()) } } /// A service level response wrapper. pub struct ServiceResponse<B = BoxBody> { request: HttpRequest, response: HttpResponse<B>, } impl ServiceResponse<BoxBody> { /// Create service response from the error pub fn from_err<E: Into<Error>>(err: E, request: HttpRequest) -> Self { let response = HttpResponse::from_error(err); ServiceResponse { request, response } } } impl<B> ServiceResponse<B> { /// Create service response instance pub fn new(request: HttpRequest, response: HttpResponse<B>) -> Self { ServiceResponse { request, response } } /// Create service response for error #[inline] pub fn error_response<E: Into<Error>>(self, err: E) -> ServiceResponse { ServiceResponse::from_err(err, self.request) } /// Create service response #[inline] pub fn into_response<B1>(self, response: HttpResponse<B1>) -> ServiceResponse<B1> { ServiceResponse::new(self.request, response) } /// Returns reference to original request. #[inline] pub fn request(&self) -> &HttpRequest { &self.request } /// Returns reference to response. #[inline] pub fn response(&self) -> &HttpResponse<B> { &self.response } /// Returns mutable reference to response. #[inline] pub fn response_mut(&mut self) -> &mut HttpResponse<B> { &mut self.response } /// Returns response status code. #[inline] pub fn status(&self) -> StatusCode { self.response.status() } /// Returns response's headers. #[inline] pub fn headers(&self) -> &HeaderMap { self.response.headers() } /// Returns mutable response's headers. #[inline] pub fn headers_mut(&mut self) -> &mut HeaderMap { self.response.headers_mut() } /// Destructures `ServiceResponse` into request and response components. #[inline] pub fn into_parts(self) -> (HttpRequest, HttpResponse<B>) { (self.request, self.response) } /// Map the current body type to another using a closure. Returns a new response. /// /// Closure receives the response head and the current body type. #[inline] pub fn map_body<F, B2>(self, f: F) -> ServiceResponse<B2> where F: FnOnce(&mut ResponseHead, B) -> B2, { let response = self.response.map_body(f); ServiceResponse { response, request: self.request, } } #[inline] pub fn map_into_left_body<R>(self) -> ServiceResponse<EitherBody<B, R>> { self.map_body(|_, body| EitherBody::left(body)) } #[inline] pub fn map_into_right_body<L>(self) -> ServiceResponse<EitherBody<L, B>> { self.map_body(|_, body| EitherBody::right(body)) } #[inline] pub fn map_into_boxed_body(self) -> ServiceResponse<BoxBody> where B: MessageBody + 'static, { self.map_body(|_, body| body.boxed()) } /// Consumes the response and returns its body. #[inline] pub fn into_body(self) -> B { self.response.into_body() } } impl<B> From<ServiceResponse<B>> for HttpResponse<B> { fn from(res: ServiceResponse<B>) -> HttpResponse<B> { res.response } } impl<B> From<ServiceResponse<B>> for Response<B> { fn from(res: ServiceResponse<B>) -> Response<B> { res.response.into() } } impl<B> fmt::Debug for ServiceResponse<B> where B: MessageBody, B::Error: Into<Error>, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let res = writeln!( f, "\nServiceResponse {:?} {}{}", self.response.head().version, self.response.head().status, self.response.head().reason.unwrap_or(""), ); let _ = writeln!(f, " headers:"); for (key, val) in self.response.head().headers.iter() { let _ = writeln!(f, " {:?}: {:?}", key, val); } let _ = writeln!(f, " body: {:?}", self.response.body().size()); res } } pub struct WebService { rdef: Patterns, name: Option<String>, guards: Vec<Box<dyn Guard>>, } impl WebService { /// Create new `WebService` instance. pub fn new<T: IntoPatterns>(path: T) -> Self { WebService { rdef: path.patterns(), name: None, guards: Vec::new(), } } /// Set service name. /// /// Name is used for URL generation. pub fn name(mut self, name: &str) -> Self { self.name = Some(name.to_string()); self } /// Add match guard to a web service. /// /// ``` /// use actix_web::{web, guard, dev, App, Error, HttpResponse}; /// /// async fn index(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> { /// Ok(req.into_response(HttpResponse::Ok().finish())) /// } /// /// let app = App::new() /// .service( /// web::service("/app") /// .guard(guard::Header("content-type", "text/plain")) /// .finish(index) /// ); /// ``` pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self { self.guards.push(Box::new(guard)); self } /// Set a service factory implementation and generate web service. pub fn finish<T, F>(self, service: F) -> impl HttpServiceFactory where F: IntoServiceFactory<T, ServiceRequest>, T: ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = (), > + 'static, { WebServiceImpl { srv: service.into_factory(), rdef: self.rdef, name: self.name, guards: self.guards, } } } struct WebServiceImpl<T> { srv: T, rdef: Patterns, name: Option<String>, guards: Vec<Box<dyn Guard>>, } impl<T> HttpServiceFactory for WebServiceImpl<T> where T: ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse, Error = Error, InitError = (), > + 'static, { fn register(mut self, config: &mut AppService) { let guards = if self.guards.is_empty() { None } else { Some(std::mem::take(&mut self.guards)) }; let mut rdef = if config.is_root() || !self.rdef.is_empty() { ResourceDef::new(ensure_leading_slash(self.rdef)) } else { ResourceDef::new(self.rdef) }; if let Some(ref name) = self.name { rdef.set_name(name); } config.register_service(rdef, guards, self.srv, None) } } /// Macro to help register different types of services at the same time. /// /// The max number of services that can be grouped together is 12 and all must implement the /// [`HttpServiceFactory`] trait. /// /// # Examples /// ``` /// use actix_web::{services, web, App}; /// /// let services = services![ /// web::resource("/test2").to(|| async { "test2" }), /// web::scope("/test3").route("/", web::get().to(|| async { "test3" })) /// ]; /// /// let app = App::new().service(services); /// /// // services macro just convert multiple services to a tuple. /// // below would also work without importing the macro. /// let app = App::new().service(( /// web::resource("/test2").to(|| async { "test2" }), /// web::scope("/test3").route("/", web::get().to(|| async { "test3" })) /// )); /// ``` #[macro_export] macro_rules! services { () => {()}; ($($x:expr),+ $(,)?) => { ($($x,)+) } } /// HttpServiceFactory trait impl for tuples macro_rules! service_tuple ({ $($T:ident)+ } => { impl<$($T: HttpServiceFactory),+> HttpServiceFactory for ($($T,)+) { #[allow(non_snake_case)] fn register(self, config: &mut AppService) { let ($($T,)*) = self; $($T.register(config);)+ } } }); service_tuple! { A } service_tuple! { A B } service_tuple! { A B C } service_tuple! { A B C D } service_tuple! { A B C D E } service_tuple! { A B C D E F } service_tuple! { A B C D E F G } service_tuple! { A B C D E F G H } service_tuple! { A B C D E F G H I } service_tuple! { A B C D E F G H I J } service_tuple! { A B C D E F G H I J K } service_tuple! { A B C D E F G H I J K L } #[cfg(test)] mod tests { use actix_service::Service; use actix_utils::future::ok; use super::*; use crate::{ guard, http, test::{self, init_service, TestRequest}, web, App, }; #[actix_rt::test] async fn test_service() { let srv = init_service( App::new().service(web::service("/test").name("test").finish( |req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())), )), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); let srv = init_service( App::new().service(web::service("/test").guard(guard::Get()).finish( |req: ServiceRequest| ok(req.into_response(HttpResponse::Ok().finish())), )), ) .await; let req = TestRequest::with_uri("/test") .method(http::Method::PUT) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::NOT_FOUND); } // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_service_data() { let srv = init_service( App::new() .data(42u32) .service( web::service("/test") .name("test") .finish(|req: ServiceRequest| { assert_eq!(req.app_data::<web::Data<u32>>().unwrap().as_ref(), &42); ok(req.into_response(HttpResponse::Ok().finish())) }), ), ) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); } #[test] fn test_fmt_debug() { let req = TestRequest::get() .uri("/index.html?test=1") .insert_header(("x-test", "111")) .to_srv_request(); let s = format!("{:?}", req); assert!(s.contains("ServiceRequest")); assert!(s.contains("test=1")); assert!(s.contains("x-test")); let res = HttpResponse::Ok().insert_header(("x-test", "111")).finish(); let res = TestRequest::post() .uri("/index.html?test=1") .to_srv_response(res); let s = format!("{:?}", res); assert!(s.contains("ServiceResponse")); assert!(s.contains("x-test")); } #[actix_rt::test] async fn test_services_macro() { let scoped = services![ web::service("/scoped_test1").name("scoped_test1").finish( |req: ServiceRequest| async { Ok(req.into_response(HttpResponse::Ok().finish())) } ), web::resource("/scoped_test2").to(|| async { "test2" }), ]; let services = services![ web::service("/test1") .name("test") .finish(|req: ServiceRequest| async { Ok(req.into_response(HttpResponse::Ok().finish())) }), web::resource("/test2").to(|| async { "test2" }), web::scope("/test3").service(scoped) ]; let srv = init_service(App::new().service(services)).await; let req = TestRequest::with_uri("/test1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); let req = TestRequest::with_uri("/test2").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); let req = TestRequest::with_uri("/test3/scoped_test1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); let req = TestRequest::with_uri("/test3/scoped_test2").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); } #[actix_rt::test] async fn test_services_vec() { let services = vec![ web::resource("/test1").to(|| async { "test1" }), web::resource("/test2").to(|| async { "test2" }), ]; let scoped = vec![ web::resource("/scoped_test1").to(|| async { "test1" }), web::resource("/scoped_test2").to(|| async { "test2" }), ]; let srv = init_service( App::new() .service(services) .service(web::scope("/test3").service(scoped)), ) .await; let req = TestRequest::with_uri("/test1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); let req = TestRequest::with_uri("/test2").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); let req = TestRequest::with_uri("/test3/scoped_test1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); let req = TestRequest::with_uri("/test3/scoped_test2").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), http::StatusCode::OK); } #[actix_rt::test] #[should_panic(expected = "called `Option::unwrap()` on a `None` value")] async fn cloning_request_panics() { async fn index(_name: web::Path<(String,)>) -> &'static str { "" } let app = test::init_service( App::new() .wrap_fn(|req, svc| { let (req, pl) = req.into_parts(); let _req2 = req.clone(); let req = ServiceRequest::from_parts(req, pl); svc.call(req) }) .route("/", web::get().to(|| async { "" })) .service(web::resource("/resource1/{name}/index.html").route(web::get().to(index))), ) .await; let req = test::TestRequest::default().to_request(); let _res = test::call_service(&app, req).await; } #[test] fn define_services_macro_with_multiple_arguments() { let result = services!(1, 2, 3); assert_eq!(result, (1, 2, 3)); } #[test] fn define_services_macro_with_single_argument() { let result = services!(1); assert_eq!(result, (1,)); } #[test] fn define_services_macro_with_no_arguments() { let result = services!(); let () = result; } #[test] fn define_services_macro_with_trailing_comma() { let result = services!(1, 2, 3,); assert_eq!(result, (1, 2, 3)); } #[test] fn define_services_macro_with_comments_in_arguments() { let result = services!( 1, // First comment 2, // Second comment 3 // Third comment ); // Assert that comments are ignored and it correctly returns a tuple. assert_eq!(result, (1, 2, 3)); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/scope.rs
actix-web/src/scope.rs
use std::{cell::RefCell, fmt, future::Future, mem, rc::Rc}; use actix_http::{body::MessageBody, Extensions}; use actix_router::{ResourceDef, Router}; use actix_service::{ apply, apply_fn_factory, boxed, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt, Transform, }; use futures_core::future::LocalBoxFuture; use futures_util::future::join_all; use crate::{ config::ServiceConfig, data::Data, dev::AppService, guard::Guard, rmap::ResourceMap, service::{ AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, HttpServiceFactory, ServiceFactoryWrapper, ServiceRequest, ServiceResponse, }, Error, Resource, Route, }; type Guards = Vec<Box<dyn Guard>>; /// A collection of [`Route`]s, [`Resource`]s, or other services that share a common path prefix. /// /// The `Scope`'s path can contain [dynamic segments]. The dynamic segments can be extracted from /// requests using the [`Path`](crate::web::Path) extractor or /// with [`HttpRequest::match_info()`](crate::HttpRequest::match_info). /// /// # Avoid Trailing Slashes /// Avoid using trailing slashes in the scope prefix (e.g., `web::scope("/scope/")`). It will almost /// certainly not have the expected behavior. See the [documentation on resource definitions][pat] /// to understand why this is the case and how to correctly construct scope/prefix definitions. /// /// # Examples /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// let app = App::new().service( /// web::scope("/{project_id}") /// .service(web::resource("/path1").to(|| async { "OK" })) /// .service(web::resource("/path2").route(web::get().to(|| HttpResponse::Ok()))) /// .service(web::resource("/path3").route(web::head().to(HttpResponse::MethodNotAllowed))) /// ); /// ``` /// /// In the above example three routes get registered: /// - /{project_id}/path1 - responds to all HTTP methods /// - /{project_id}/path2 - responds to `GET` requests /// - /{project_id}/path3 - responds to `HEAD` requests /// /// [pat]: crate::dev::ResourceDef#prefix-resources /// [dynamic segments]: crate::dev::ResourceDef#dynamic-segments pub struct Scope<T = ScopeEndpoint> { endpoint: T, rdef: String, app_data: Option<Extensions>, services: Vec<Box<dyn AppServiceFactory>>, guards: Vec<Box<dyn Guard>>, default: Option<Rc<BoxedHttpServiceFactory>>, external: Vec<ResourceDef>, factory_ref: Rc<RefCell<Option<ScopeFactory>>>, } impl Scope { /// Create a new scope pub fn new(path: &str) -> Scope { let factory_ref = Rc::new(RefCell::new(None)); Scope { endpoint: ScopeEndpoint::new(Rc::clone(&factory_ref)), rdef: path.to_string(), app_data: None, guards: Vec::new(), services: Vec::new(), default: None, external: Vec::new(), factory_ref, } } } impl<T> Scope<T> where T: ServiceFactory<ServiceRequest, Config = (), Error = Error, InitError = ()>, { /// Add match guard to a scope. /// /// ``` /// use actix_web::{web, guard, App, HttpRequest, HttpResponse}; /// /// async fn index(data: web::Path<(String, String)>) -> &'static str { /// "Welcome!" /// } /// /// let app = App::new().service( /// web::scope("/app") /// .guard(guard::Header("content-type", "text/plain")) /// .route("/test1", web::get().to(index)) /// .route("/test2", web::post().to(|r: HttpRequest| { /// HttpResponse::MethodNotAllowed() /// })) /// ); /// ``` pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self { self.guards.push(Box::new(guard)); self } /// Add scope data. /// /// Data of different types from parent contexts will still be accessible. Any `Data<T>` types /// set here can be extracted in handlers using the `Data<T>` extractor. /// /// # Examples /// ``` /// use std::cell::Cell; /// use actix_web::{web, App, HttpRequest, HttpResponse, Responder}; /// /// struct MyData { /// count: std::cell::Cell<usize>, /// } /// /// async fn handler(req: HttpRequest, counter: web::Data<MyData>) -> impl Responder { /// // note this cannot use the Data<T> extractor because it was not added with it /// let incr = *req.app_data::<usize>().unwrap(); /// assert_eq!(incr, 3); /// /// // update counter using other value from app data /// counter.count.set(counter.count.get() + incr); /// /// HttpResponse::Ok().body(counter.count.get().to_string()) /// } /// /// let app = App::new().service( /// web::scope("/app") /// .app_data(3usize) /// .app_data(web::Data::new(MyData { count: Default::default() })) /// .route("/", web::get().to(handler)) /// ); /// ``` #[doc(alias = "manage")] pub fn app_data<U: 'static>(mut self, data: U) -> Self { self.app_data .get_or_insert_with(Extensions::new) .insert(data); self } /// Add scope data after wrapping in `Data<T>`. /// /// Deprecated in favor of [`app_data`](Self::app_data). #[deprecated(since = "4.0.0", note = "Use `.app_data(Data::new(val))` instead.")] pub fn data<U: 'static>(self, data: U) -> Self { self.app_data(Data::new(data)) } /// Run external configuration as part of the scope building process. /// /// This function is useful for moving parts of configuration to a different module or library. /// For example, some of the resource's configuration could be moved to different module. /// /// ``` /// use actix_web::{web, middleware, App, HttpResponse}; /// /// // this function could be located in different module /// fn config(cfg: &mut web::ServiceConfig) { /// cfg.service(web::resource("/test") /// .route(web::get().to(|| HttpResponse::Ok())) /// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) /// ); /// } /// /// let app = App::new() /// .wrap(middleware::Logger::default()) /// .service( /// web::scope("/api") /// .configure(config) /// ) /// .route("/index.html", web::get().to(|| HttpResponse::Ok())); /// ``` pub fn configure<F>(mut self, cfg_fn: F) -> Self where F: FnOnce(&mut ServiceConfig), { let mut cfg = ServiceConfig::new(); cfg_fn(&mut cfg); self.services.extend(cfg.services); self.external.extend(cfg.external); // TODO: add Extensions::is_empty check and conditionally insert data self.app_data .get_or_insert_with(Extensions::new) .extend(cfg.app_data); if let Some(default) = cfg.default { self.default = Some(default); } self } /// Register HTTP service. /// /// This is similar to `App's` service registration. /// /// Actix Web provides several services implementations: /// /// * *Resource* is an entry in resource table which corresponds to requested URL. /// * *Scope* is a set of resources with common root path. /// /// ``` /// use actix_web::{web, App, HttpRequest}; /// /// struct AppState; /// /// async fn index(req: HttpRequest) -> &'static str { /// "Welcome!" /// } /// /// let app = App::new().service( /// web::scope("/app").service( /// web::scope("/v1") /// .service(web::resource("/test1").to(index))) /// ); /// ``` pub fn service<F>(mut self, factory: F) -> Self where F: HttpServiceFactory + 'static, { self.services .push(Box::new(ServiceFactoryWrapper::new(factory))); self } /// Configure route for a specific path. /// /// This is a simplified version of the `Scope::service()` method. /// This method can be called multiple times, in that case /// multiple resources with one route would be registered for same resource path. /// /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// async fn index(data: web::Path<(String, String)>) -> &'static str { /// "Welcome!" /// } /// /// let app = App::new().service( /// web::scope("/app") /// .route("/test1", web::get().to(index)) /// .route("/test2", web::post().to(|| HttpResponse::MethodNotAllowed())) /// ); /// ``` pub fn route(self, path: &str, mut route: Route) -> Self { self.service( Resource::new(path) .add_guards(route.take_guards()) .route(route), ) } /// Default service to be used if no matching resource could be found. /// /// If a default service is not registered, it will fall back to the default service of /// the parent [`App`](crate::App) (see [`App::default_service`](crate::App::default_service)). pub fn default_service<F, U>(mut self, f: F) -> Self where F: IntoServiceFactory<U, ServiceRequest>, U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static, U::InitError: fmt::Debug, { // create and configure default resource self.default = Some(Rc::new(boxed::factory(f.into_factory().map_init_err( |err| { log::error!("Can not construct default service: {err:?}"); }, )))); self } /// Registers a scope-wide middleware. /// /// `mw` is a middleware component (type), that can modify the request and response across all /// sub-resources managed by this `Scope`. /// /// See [`App::wrap`](crate::App::wrap) for more details. #[doc(alias = "middleware")] #[doc(alias = "use")] // nodejs terminology pub fn wrap<M, B>( self, mw: M, ) -> Scope< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, > where M: Transform< T::Service, ServiceRequest, Response = ServiceResponse<B>, Error = Error, InitError = (), > + 'static, B: MessageBody, { Scope { endpoint: apply(mw, self.endpoint), rdef: self.rdef, app_data: self.app_data, guards: self.guards, services: self.services, default: self.default, external: self.external, factory_ref: self.factory_ref, } } /// Registers a scope-wide function middleware. /// /// `mw` is a closure that runs during inbound and/or outbound processing in the request /// life-cycle (request -> response), modifying request/response as necessary, across all /// requests handled by the `Scope`. /// /// See [`App::wrap_fn`](crate::App::wrap_fn) for examples and more details. #[doc(alias = "middleware")] #[doc(alias = "use")] // nodejs terminology pub fn wrap_fn<F, R, B>( self, mw: F, ) -> Scope< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, > where F: Fn(ServiceRequest, &T::Service) -> R + Clone + 'static, R: Future<Output = Result<ServiceResponse<B>, Error>>, B: MessageBody, { Scope { endpoint: apply_fn_factory(self.endpoint, mw), rdef: self.rdef, app_data: self.app_data, guards: self.guards, services: self.services, default: self.default, external: self.external, factory_ref: self.factory_ref, } } } impl<T, B> HttpServiceFactory for Scope<T> where T: ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), > + 'static, B: MessageBody + 'static, { fn register(mut self, config: &mut AppService) { // update default resource if needed let default = self.default.unwrap_or_else(|| config.default_service()); // register nested services let mut cfg = config.clone_config(); self.services .into_iter() .for_each(|mut srv| srv.register(&mut cfg)); let mut rmap = ResourceMap::new(ResourceDef::root_prefix(&self.rdef)); // external resources for mut rdef in mem::take(&mut self.external) { rmap.add(&mut rdef, None); } // complete scope pipeline creation *self.factory_ref.borrow_mut() = Some(ScopeFactory { default, services: cfg .into_services() .1 .into_iter() .map(|(mut rdef, srv, guards, nested)| { rmap.add(&mut rdef, nested); (rdef, srv, RefCell::new(guards)) }) .collect::<Vec<_>>() .into_boxed_slice() .into(), }); // get guards let guards = if self.guards.is_empty() { None } else { Some(self.guards) }; let scope_data = self.app_data.map(Rc::new); // wraps endpoint service (including middleware) call and injects app data for this scope let endpoint = apply_fn_factory(self.endpoint, move |mut req: ServiceRequest, srv| { if let Some(ref data) = scope_data { req.add_data_container(Rc::clone(data)); } let fut = srv.call(req); async { Ok(fut.await?.map_into_boxed_body()) } }); // register final service config.register_service( ResourceDef::root_prefix(&self.rdef), guards, endpoint, Some(Rc::new(rmap)), ) } } pub struct ScopeFactory { #[allow(clippy::type_complexity)] services: Rc< [( ResourceDef, BoxedHttpServiceFactory, RefCell<Option<Guards>>, )], >, default: Rc<BoxedHttpServiceFactory>, } impl ServiceFactory<ServiceRequest> for ScopeFactory { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = ScopeService; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { // construct default service factory future let default_fut = self.default.new_service(()); // construct all services factory future with it's resource def and guards. let factory_fut = join_all(self.services.iter().map(|(path, factory, guards)| { let path = path.clone(); let guards = guards.borrow_mut().take().unwrap_or_default(); let factory_fut = factory.new_service(()); async move { factory_fut .await .map(move |service| (path, guards, service)) } })); Box::pin(async move { let default = default_fut.await?; // build router from the factory future result. let router = factory_fut .await .into_iter() .collect::<Result<Vec<_>, _>>()? .drain(..) .fold(Router::build(), |mut router, (path, guards, service)| { router.push(path, service, guards); router }) .finish(); Ok(ScopeService { router, default }) }) } } pub struct ScopeService { router: Router<BoxedHttpService, Vec<Box<dyn Guard>>>, default: BoxedHttpService, } impl Service<ServiceRequest> for ScopeService { type Response = ServiceResponse; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, mut req: ServiceRequest) -> Self::Future { let res = self.router.recognize_fn(&mut req, |req, guards| { let guard_ctx = req.guard_ctx(); guards.iter().all(|guard| guard.check(&guard_ctx)) }); if let Some((srv, _info)) = res { srv.call(req) } else { self.default.call(req) } } } #[doc(hidden)] pub struct ScopeEndpoint { factory: Rc<RefCell<Option<ScopeFactory>>>, } impl ScopeEndpoint { fn new(factory: Rc<RefCell<Option<ScopeFactory>>>) -> Self { ScopeEndpoint { factory } } } impl ServiceFactory<ServiceRequest> for ScopeEndpoint { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = ScopeService; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { self.factory.borrow_mut().as_mut().unwrap().new_service(()) } } #[cfg(test)] mod tests { use actix_utils::future::ok; use bytes::Bytes; use super::*; use crate::{ guard, http::{ header::{self, HeaderValue}, Method, StatusCode, }, middleware::DefaultHeaders, test::{assert_body_eq, call_service, init_service, read_body, TestRequest}, web, App, HttpMessage, HttpRequest, HttpResponse, }; #[test] fn can_be_returned_from_fn() { fn my_scope_1() -> Scope { web::scope("/test") .service(web::resource("").route(web::get().to(|| async { "hello" }))) } fn my_scope_2() -> Scope< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<impl MessageBody>, Error = Error, InitError = (), >, > { web::scope("/test-compat") .wrap_fn(|req, srv| { let fut = srv.call(req); async { Ok(fut.await?.map_into_right_body::<()>()) } }) .service(web::resource("").route(web::get().to(|| async { "hello" }))) } fn my_scope_3() -> impl HttpServiceFactory { my_scope_2() } App::new() .service(my_scope_1()) .service(my_scope_2()) .service(my_scope_3()); } #[actix_rt::test] async fn test_scope() { let srv = init_service( App::new() .service(web::scope("/app").service(web::resource("/path1").to(HttpResponse::Ok))), ) .await; let req = TestRequest::with_uri("/app/path1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_scope_root() { let srv = init_service( App::new().service( web::scope("/app") .service(web::resource("").to(HttpResponse::Ok)) .service(web::resource("/").to(HttpResponse::Created)), ), ) .await; let req = TestRequest::with_uri("/app").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/app/").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::CREATED); } #[actix_rt::test] async fn test_scope_root2() { let srv = init_service( App::new().service(web::scope("/app/").service(web::resource("").to(HttpResponse::Ok))), ) .await; let req = TestRequest::with_uri("/app").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); let req = TestRequest::with_uri("/app/").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_scope_root3() { let srv = init_service( App::new() .service(web::scope("/app/").service(web::resource("/").to(HttpResponse::Ok))), ) .await; let req = TestRequest::with_uri("/app").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); let req = TestRequest::with_uri("/app/").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_scope_route() { let srv = init_service( App::new().service( web::scope("app") .route("/path1", web::get().to(HttpResponse::Ok)) .route("/path1", web::delete().to(HttpResponse::Ok)), ), ) .await; let req = TestRequest::with_uri("/app/path1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/app/path1") .method(Method::DELETE) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/app/path1") .method(Method::POST) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_scope_route_without_leading_slash() { let srv = init_service( App::new().service( web::scope("app").service( web::resource("path1") .route(web::get().to(HttpResponse::Ok)) .route(web::delete().to(HttpResponse::Ok)), ), ), ) .await; let req = TestRequest::with_uri("/app/path1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/app/path1") .method(Method::DELETE) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/app/path1") .method(Method::POST) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); } #[actix_rt::test] async fn test_scope_guard() { let srv = init_service( App::new().service( web::scope("/app") .guard(guard::Get()) .service(web::resource("/path1").to(HttpResponse::Ok)), ), ) .await; let req = TestRequest::with_uri("/app/path1") .method(Method::POST) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); let req = TestRequest::with_uri("/app/path1") .method(Method::GET) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_scope_variable_segment() { let srv = init_service(App::new().service(web::scope("/ab-{project}").service( web::resource("/path1").to(|r: HttpRequest| { HttpResponse::Ok().body(format!("project: {}", &r.match_info()["project"])) }), ))) .await; let req = TestRequest::with_uri("/ab-project1/path1").to_request(); let res = srv.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::OK); assert_body_eq!(res, b"project: project1"); let req = TestRequest::with_uri("/aa-project1/path1").to_request(); let res = srv.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_nested_scope() { let srv = init_service(App::new().service(web::scope("/app").service( web::scope("/t1").service(web::resource("/path1").to(HttpResponse::Created)), ))) .await; let req = TestRequest::with_uri("/app/t1/path1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::CREATED); } #[actix_rt::test] async fn test_nested_scope_no_slash() { let srv = init_service(App::new().service(web::scope("/app").service( web::scope("t1").service(web::resource("/path1").to(HttpResponse::Created)), ))) .await; let req = TestRequest::with_uri("/app/t1/path1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::CREATED); } #[actix_rt::test] async fn test_nested_scope_root() { let srv = init_service( App::new().service( web::scope("/app").service( web::scope("/t1") .service(web::resource("").to(HttpResponse::Ok)) .service(web::resource("/").to(HttpResponse::Created)), ), ), ) .await; let req = TestRequest::with_uri("/app/t1").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/app/t1/").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::CREATED); } #[actix_rt::test] async fn test_nested_scope_filter() { let srv = init_service( App::new().service( web::scope("/app").service( web::scope("/t1") .guard(guard::Get()) .service(web::resource("/path1").to(HttpResponse::Ok)), ), ), ) .await; let req = TestRequest::with_uri("/app/t1/path1") .method(Method::POST) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); let req = TestRequest::with_uri("/app/t1/path1") .method(Method::GET) .to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_nested_scope_with_variable_segment() { let srv = init_service(App::new().service(web::scope("/app").service( web::scope("/{project_id}").service(web::resource("/path1").to(|r: HttpRequest| { HttpResponse::Created().body(format!("project: {}", &r.match_info()["project_id"])) })), ))) .await; let req = TestRequest::with_uri("/app/project_1/path1").to_request(); let res = srv.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::CREATED); assert_body_eq!(res, b"project: project_1"); } #[actix_rt::test] async fn test_nested2_scope_with_variable_segment() { let srv = init_service(App::new().service(web::scope("/app").service( web::scope("/{project}").service(web::scope("/{id}").service( web::resource("/path1").to(|r: HttpRequest| { HttpResponse::Created().body(format!( "project: {} - {}", &r.match_info()["project"], &r.match_info()["id"], )) }), )), ))) .await; let req = TestRequest::with_uri("/app/test/1/path1").to_request(); let res = srv.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::CREATED); assert_body_eq!(res, b"project: test - 1"); let req = TestRequest::with_uri("/app/test/1/path2").to_request(); let res = srv.call(req).await.unwrap(); assert_eq!(res.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_default_resource() { let srv = init_service( App::new().service( web::scope("/app") .service(web::resource("/path1").to(HttpResponse::Ok)) .default_service(|r: ServiceRequest| { ok(r.into_response(HttpResponse::BadRequest())) }), ), ) .await; let req = TestRequest::with_uri("/app/path2").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/path2").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_default_resource_propagation() { let srv = init_service( App::new() .service(web::scope("/app1").default_service(web::to(HttpResponse::BadRequest))) .service(web::scope("/app2")) .default_service(|r: ServiceRequest| { ok(r.into_response(HttpResponse::MethodNotAllowed())) }), ) .await; let req = TestRequest::with_uri("/non-exist").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); let req = TestRequest::with_uri("/app1/non-exist").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/app2/non-exist").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); } #[actix_rt::test] async fn test_middleware() { let srv = init_service( App::new().service( web::scope("app") .wrap( DefaultHeaders::new() .add((header::CONTENT_TYPE, HeaderValue::from_static("0001"))), ) .service(web::resource("/test").route(web::get().to(HttpResponse::Ok))), ), ) .await; let req = TestRequest::with_uri("/app/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), HeaderValue::from_static("0001") ); } #[actix_rt::test] async fn test_middleware_body_type() { // Compile test that Scope accepts any body type; test for `EitherBody` let srv = init_service( App::new().service( web::scope("app") .wrap_fn(|req, srv| { let fut = srv.call(req); async { Ok(fut.await?.map_into_right_body::<()>()) } }) .service(web::resource("/test").route(web::get().to(|| async { "hello" }))), ), ) .await; // test if `MessageBody::try_into_bytes()` is preserved across scope layer use actix_http::body::MessageBody as _; let req = TestRequest::with_uri("/app/test").to_request(); let resp = call_service(&srv, req).await; let body = resp.into_body(); assert_eq!(body.try_into_bytes().unwrap(), b"hello".as_ref()); } #[actix_rt::test] async fn test_middleware_fn() { let srv = init_service( App::new().service( web::scope("app") .wrap_fn(|req, srv| { let fut = srv.call(req); async move { let mut res = fut.await?;
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
true
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/app_service.rs
actix-web/src/app_service.rs
use std::{cell::RefCell, mem, rc::Rc}; use actix_http::Request; use actix_router::{Path, ResourceDef, Router, Url}; use actix_service::{boxed, fn_service, Service, ServiceFactory}; use futures_core::future::LocalBoxFuture; use futures_util::future::join_all; use crate::{ body::BoxBody, config::{AppConfig, AppService}, data::FnDataFactory, dev::Extensions, guard::Guard, request::{HttpRequest, HttpRequestPool}, rmap::ResourceMap, service::{ AppServiceFactory, BoxedHttpService, BoxedHttpServiceFactory, ServiceRequest, ServiceResponse, }, Error, HttpResponse, }; /// Service factory to convert [`Request`] to a [`ServiceRequest<S>`]. /// /// It also executes data factories. pub struct AppInit<T, B> where T: ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, { pub(crate) endpoint: T, pub(crate) extensions: RefCell<Option<Extensions>>, pub(crate) async_data_factories: Rc<[FnDataFactory]>, pub(crate) services: Rc<RefCell<Vec<Box<dyn AppServiceFactory>>>>, pub(crate) default: Option<Rc<BoxedHttpServiceFactory>>, pub(crate) factory_ref: Rc<RefCell<Option<AppRoutingFactory>>>, pub(crate) external: RefCell<Vec<ResourceDef>>, } impl<T, B> ServiceFactory<Request> for AppInit<T, B> where T: ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, T::Future: 'static, { type Response = ServiceResponse<B>; type Error = T::Error; type Config = AppConfig; type Service = AppInitService<T::Service, B>; type InitError = T::InitError; type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, config: AppConfig) -> Self::Future { // set AppService's default service to 404 NotFound // if no user defined default service exists. let default = self.default.clone().unwrap_or_else(|| { Rc::new(boxed::factory(fn_service(|req: ServiceRequest| async { Ok(req.into_response(HttpResponse::NotFound())) }))) }); // create App config to pass to child services let mut config = AppService::new(config, Rc::clone(&default)); // register services mem::take(&mut *self.services.borrow_mut()) .into_iter() .for_each(|mut srv| srv.register(&mut config)); let mut rmap = ResourceMap::new(ResourceDef::prefix("")); let (config, services) = config.into_services(); // complete pipeline creation. *self.factory_ref.borrow_mut() = Some(AppRoutingFactory { default, services: services .into_iter() .map(|(mut rdef, srv, guards, nested)| { rmap.add(&mut rdef, nested); (rdef, srv, RefCell::new(guards)) }) .collect::<Vec<_>>() .into_boxed_slice() .into(), }); // external resources for mut rdef in mem::take(&mut *self.external.borrow_mut()) { rmap.add(&mut rdef, None); } // complete ResourceMap tree creation let rmap = Rc::new(rmap); ResourceMap::finish(&rmap); // construct all async data factory futures let factory_futs = join_all(self.async_data_factories.iter().map(|f| f())); // construct app service and middleware service factory future. let endpoint_fut = self.endpoint.new_service(()); // take extensions or create new one as app data container. let mut app_data = self.extensions.borrow_mut().take().unwrap_or_default(); Box::pin(async move { // async data factories let async_data_factories = factory_futs .await .into_iter() .collect::<Result<Vec<_>, _>>() .map_err(|_| ())?; // app service and middleware let service = endpoint_fut.await?; // populate app data container from (async) data factories. for factory in &async_data_factories { factory.create(&mut app_data); } Ok(AppInitService { service, app_data: Rc::new(app_data), app_state: AppInitServiceState::new(rmap, config), }) }) } } /// The [`Service`] that is passed to `actix-http`'s server builder. /// /// Wraps a service receiving a [`ServiceRequest`] into one receiving a [`Request`]. pub struct AppInitService<T, B> where T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, { service: T, app_data: Rc<Extensions>, app_state: Rc<AppInitServiceState>, } /// A collection of state for [`AppInitService`] that is shared across [`HttpRequest`]s. pub(crate) struct AppInitServiceState { rmap: Rc<ResourceMap>, config: AppConfig, pool: HttpRequestPool, } impl AppInitServiceState { /// Constructs state collection from resource map and app config. pub(crate) fn new(rmap: Rc<ResourceMap>, config: AppConfig) -> Rc<Self> { Rc::new(AppInitServiceState { rmap, config, pool: HttpRequestPool::default(), }) } /// Returns a reference to the application's resource map. #[inline] pub(crate) fn rmap(&self) -> &ResourceMap { &self.rmap } /// Returns a reference to the application's configuration. #[inline] pub(crate) fn config(&self) -> &AppConfig { &self.config } /// Returns a reference to the application's request pool. #[inline] pub(crate) fn pool(&self) -> &HttpRequestPool { &self.pool } } impl<T, B> Service<Request> for AppInitService<T, B> where T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, { type Response = ServiceResponse<B>; type Error = T::Error; type Future = T::Future; actix_service::forward_ready!(service); fn call(&self, mut req: Request) -> Self::Future { let extensions = Rc::new(RefCell::new(req.take_req_data())); let conn_data = req.take_conn_data(); let (head, payload) = req.into_parts(); let req = match self.app_state.pool().pop() { Some(mut req) => { let inner = Rc::get_mut(&mut req.inner).unwrap(); inner.path.get_mut().update(&head.uri); inner.path.reset(); inner.head = head; inner.conn_data = conn_data; inner.extensions = extensions; req } None => HttpRequest::new( Path::new(Url::new(head.uri.clone())), head, Rc::clone(&self.app_state), Rc::clone(&self.app_data), conn_data, extensions, ), }; self.service.call(ServiceRequest::new(req, payload)) } } impl<T, B> Drop for AppInitService<T, B> where T: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, { fn drop(&mut self) { self.app_state.pool().clear(); } } pub struct AppRoutingFactory { #[allow(clippy::type_complexity)] services: Rc< [( ResourceDef, BoxedHttpServiceFactory, RefCell<Option<Vec<Box<dyn Guard>>>>, )], >, default: Rc<BoxedHttpServiceFactory>, } impl ServiceFactory<ServiceRequest> for AppRoutingFactory { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = AppRouting; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { // construct all services factory future with its resource def and guards. let factory_fut = join_all(self.services.iter().map(|(path, factory, guards)| { let path = path.clone(); let guards = guards.borrow_mut().take().unwrap_or_default(); let factory_fut = factory.new_service(()); async move { factory_fut .await .map(move |service| (path, guards, service)) } })); // construct default service factory future let default_fut = self.default.new_service(()); Box::pin(async move { let default = default_fut.await?; // build router from the factory future result. let router = factory_fut .await .into_iter() .collect::<Result<Vec<_>, _>>()? .drain(..) .fold(Router::build(), |mut router, (path, guards, service)| { router.push(path, service, guards); router }) .finish(); Ok(AppRouting { router, default }) }) } } /// The Actix Web router default entry point. pub struct AppRouting { router: Router<BoxedHttpService, Vec<Box<dyn Guard>>>, default: BoxedHttpService, } impl Service<ServiceRequest> for AppRouting { type Response = ServiceResponse<BoxBody>; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_service::always_ready!(); fn call(&self, mut req: ServiceRequest) -> Self::Future { let res = self.router.recognize_fn(&mut req, |req, guards| { let guard_ctx = req.guard_ctx(); guards.iter().all(|guard| guard.check(&guard_ctx)) }); if let Some((srv, _info)) = res { srv.call(req) } else { self.default.call(req) } } } /// Wrapper service for routing pub struct AppEntry { factory: Rc<RefCell<Option<AppRoutingFactory>>>, } impl AppEntry { pub fn new(factory: Rc<RefCell<Option<AppRoutingFactory>>>) -> Self { AppEntry { factory } } } impl ServiceFactory<ServiceRequest> for AppEntry { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = AppRouting; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { self.factory.borrow_mut().as_mut().unwrap().new_service(()) } } #[cfg(test)] mod tests { use std::sync::{ atomic::{AtomicBool, Ordering}, Arc, }; use actix_service::Service; use crate::{ test::{init_service, TestRequest}, web, App, HttpResponse, }; struct DropData(Arc<AtomicBool>); impl Drop for DropData { fn drop(&mut self) { self.0.store(true, Ordering::Relaxed); } } // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_drop_data() { let data = Arc::new(AtomicBool::new(false)); { let app = init_service( App::new() .data(DropData(data.clone())) .service(web::resource("/test").to(HttpResponse::Ok)), ) .await; let req = TestRequest::with_uri("/test").to_request(); let _ = app.call(req).await.unwrap(); } assert!(data.load(Ordering::Relaxed)); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/rmap.rs
actix-web/src/rmap.rs
use std::{ borrow::Cow, cell::RefCell, fmt::Write as _, rc::{Rc, Weak}, }; use actix_router::ResourceDef; use foldhash::HashMap as FoldHashMap; use url::Url; use crate::{error::UrlGenerationError, request::HttpRequest}; const AVG_PATH_LEN: usize = 24; #[derive(Clone, Debug)] pub struct ResourceMap { pattern: ResourceDef, /// Named resources within the tree or, for external resources, it points to isolated nodes /// outside the tree. named: FoldHashMap<String, Rc<ResourceMap>>, parent: RefCell<Weak<ResourceMap>>, /// Must be `None` for "edge" nodes. nodes: Option<Vec<Rc<ResourceMap>>>, } impl ResourceMap { /// Creates a _container_ node in the `ResourceMap` tree. pub fn new(root: ResourceDef) -> Self { ResourceMap { pattern: root, named: FoldHashMap::default(), parent: RefCell::new(Weak::new()), nodes: Some(Vec::new()), } } /// Format resource map as tree structure (unfinished). #[allow(dead_code)] pub(crate) fn tree(&self) -> String { let mut buf = String::new(); self._tree(&mut buf, 0); buf } pub(crate) fn _tree(&self, buf: &mut String, level: usize) { if let Some(children) = &self.nodes { for child in children { writeln!( buf, "{}{} {}", "--".repeat(level), child.pattern.pattern().unwrap(), child .pattern .name() .map(|name| format!("({})", name)) .unwrap_or_else(|| "".to_owned()) ) .unwrap(); ResourceMap::_tree(child, buf, level + 1); } } } /// Adds a (possibly nested) resource. /// /// To add a non-prefix pattern, `nested` must be `None`. /// To add external resource, supply a pattern without a leading `/`. /// The root pattern of `nested`, if present, should match `pattern`. pub fn add(&mut self, pattern: &mut ResourceDef, nested: Option<Rc<ResourceMap>>) { pattern.set_id(self.nodes.as_ref().unwrap().len() as u16); if let Some(new_node) = nested { debug_assert_eq!( &new_node.pattern, pattern, "`pattern` and `nested` mismatch" ); // parents absorb references to the named resources of children self.named.extend(new_node.named.clone()); self.nodes.as_mut().unwrap().push(new_node); } else { let new_node = Rc::new(ResourceMap { pattern: pattern.clone(), named: FoldHashMap::default(), parent: RefCell::new(Weak::new()), nodes: None, }); if let Some(name) = pattern.name() { self.named.insert(name.to_owned(), Rc::clone(&new_node)); } let is_external = match pattern.pattern() { Some(p) => !p.is_empty() && !p.starts_with('/'), None => false, }; // don't add external resources to the tree if !is_external { self.nodes.as_mut().unwrap().push(new_node); } } } pub(crate) fn finish(self: &Rc<Self>) { for node in self.nodes.iter().flatten() { node.parent.replace(Rc::downgrade(self)); ResourceMap::finish(node); } } /// Generate URL for named resource. /// /// Check [`HttpRequest::url_for`] for detailed information. pub fn url_for<U, I>( &self, req: &HttpRequest, name: &str, elements: U, ) -> Result<Url, UrlGenerationError> where U: IntoIterator<Item = I>, I: AsRef<str>, { let mut elements = elements.into_iter(); let path = self .named .get(name) .ok_or(UrlGenerationError::ResourceNotFound)? .root_rmap_fn(String::with_capacity(AVG_PATH_LEN), |mut acc, node| { node.pattern .resource_path_from_iter(&mut acc, &mut elements) .then_some(acc) }) .ok_or(UrlGenerationError::NotEnoughElements)?; let (base, path): (Cow<'_, _>, _) = if path.starts_with('/') { // build full URL from connection info parts and resource path let conn = req.connection_info(); let base = format!("{}://{}", conn.scheme(), conn.host()); (Cow::Owned(base), path.as_str()) } else { // external resource; third slash would be the root slash in the path let third_slash_index = path .char_indices() .filter_map(|(i, c)| (c == '/').then_some(i)) .nth(2) .unwrap_or(path.len()); ( Cow::Borrowed(&path[..third_slash_index]), &path[third_slash_index..], ) }; let mut url = Url::parse(&base)?; url.set_path(path); Ok(url) } /// Returns true if there is a resource that would match `path`. pub fn has_resource(&self, path: &str) -> bool { self.find_matching_node(path).is_some() } /// Returns the name of the route that matches the given path or None if no full match /// is possible or the matching resource is not named. pub fn match_name(&self, path: &str) -> Option<&str> { self.find_matching_node(path)?.pattern.name() } /// Returns the full resource pattern matched against a path or None if no full match /// is possible. pub fn match_pattern(&self, path: &str) -> Option<String> { self.find_matching_node(path)?.root_rmap_fn( String::with_capacity(AVG_PATH_LEN), |mut acc, node| { let pattern = node.pattern.pattern()?; acc.push_str(pattern); Some(acc) }, ) } fn find_matching_node(&self, path: &str) -> Option<&ResourceMap> { self._find_matching_node(path).flatten() } /// Returns `None` if root pattern doesn't match; /// `Some(None)` if root pattern matches but there is no matching child pattern. /// Don't search sideways when `Some(none)` is returned. fn _find_matching_node(&self, path: &str) -> Option<Option<&ResourceMap>> { let matched_len = self.pattern.find_match(path)?; let path = &path[matched_len..]; Some(match &self.nodes { // find first sub-node to match remaining path Some(nodes) => nodes .iter() .filter_map(|node| node._find_matching_node(path)) .next() .flatten(), // only terminate at edge nodes None => Some(self), }) } /// Find `self`'s highest ancestor and then run `F`, providing `B`, in that rmap context. fn root_rmap_fn<F, B>(&self, init: B, mut f: F) -> Option<B> where F: FnMut(B, &ResourceMap) -> Option<B>, { self._root_rmap_fn(init, &mut f) } /// Run `F`, providing `B`, if `self` is top-level resource map, else recurse to parent map. fn _root_rmap_fn<F, B>(&self, init: B, f: &mut F) -> Option<B> where F: FnMut(B, &ResourceMap) -> Option<B>, { let data = match self.parent.borrow().upgrade() { Some(ref parent) => parent._root_rmap_fn(init, f)?, None => init, }; f(data, self) } } #[cfg(test)] mod tests { use super::*; #[test] fn extract_matched_pattern() { let mut root = ResourceMap::new(ResourceDef::root_prefix("")); let mut user_map = ResourceMap::new(ResourceDef::root_prefix("/user/{id}")); user_map.add(&mut ResourceDef::new("/"), None); user_map.add(&mut ResourceDef::new("/profile"), None); user_map.add(&mut ResourceDef::new("/article/{id}"), None); user_map.add(&mut ResourceDef::new("/post/{post_id}"), None); user_map.add( &mut ResourceDef::new("/post/{post_id}/comment/{comment_id}"), None, ); root.add(&mut ResourceDef::new("/info"), None); root.add(&mut ResourceDef::new("/v{version:[[:digit:]]{1}}"), None); root.add( &mut ResourceDef::root_prefix("/user/{id}"), Some(Rc::new(user_map)), ); root.add(&mut ResourceDef::new("/info"), None); let root = Rc::new(root); ResourceMap::finish(&root); // sanity check resource map setup assert!(root.has_resource("/info")); assert!(!root.has_resource("/bar")); assert!(root.has_resource("/v1")); assert!(root.has_resource("/v2")); assert!(!root.has_resource("/v33")); assert!(!root.has_resource("/user/22")); assert!(root.has_resource("/user/22/")); assert!(root.has_resource("/user/22/profile")); // extract patterns from paths assert!(root.match_pattern("/bar").is_none()); assert!(root.match_pattern("/v44").is_none()); assert_eq!(root.match_pattern("/info"), Some("/info".to_owned())); assert_eq!( root.match_pattern("/v1"), Some("/v{version:[[:digit:]]{1}}".to_owned()) ); assert_eq!( root.match_pattern("/v2"), Some("/v{version:[[:digit:]]{1}}".to_owned()) ); assert_eq!( root.match_pattern("/user/22/profile"), Some("/user/{id}/profile".to_owned()) ); assert_eq!( root.match_pattern("/user/602CFB82-7709-4B17-ADCF-4C347B6F2203/profile"), Some("/user/{id}/profile".to_owned()) ); assert_eq!( root.match_pattern("/user/22/article/44"), Some("/user/{id}/article/{id}".to_owned()) ); assert_eq!( root.match_pattern("/user/22/post/my-post"), Some("/user/{id}/post/{post_id}".to_owned()) ); assert_eq!( root.match_pattern("/user/22/post/other-post/comment/42"), Some("/user/{id}/post/{post_id}/comment/{comment_id}".to_owned()) ); } #[test] fn extract_matched_name() { let mut root = ResourceMap::new(ResourceDef::root_prefix("")); let mut rdef = ResourceDef::new("/info"); rdef.set_name("root_info"); root.add(&mut rdef, None); let mut user_map = ResourceMap::new(ResourceDef::root_prefix("/user/{id}")); let mut rdef = ResourceDef::new("/"); user_map.add(&mut rdef, None); let mut rdef = ResourceDef::new("/post/{post_id}"); rdef.set_name("user_post"); user_map.add(&mut rdef, None); root.add( &mut ResourceDef::root_prefix("/user/{id}"), Some(Rc::new(user_map)), ); let root = Rc::new(root); ResourceMap::finish(&root); // sanity check resource map setup assert!(root.has_resource("/info")); assert!(!root.has_resource("/bar")); assert!(!root.has_resource("/user/22")); assert!(root.has_resource("/user/22/")); assert!(root.has_resource("/user/22/post/55")); // extract patterns from paths assert!(root.match_name("/bar").is_none()); assert!(root.match_name("/v44").is_none()); assert_eq!(root.match_name("/info"), Some("root_info")); assert_eq!(root.match_name("/user/22"), None); assert_eq!(root.match_name("/user/22/"), None); assert_eq!(root.match_name("/user/22/post/55"), Some("user_post")); } #[test] fn bug_fix_issue_1582_debug_print_exits() { // ref: https://github.com/actix/actix-web/issues/1582 let mut root = ResourceMap::new(ResourceDef::root_prefix("")); let mut user_map = ResourceMap::new(ResourceDef::root_prefix("/user/{id}")); user_map.add(&mut ResourceDef::new("/"), None); user_map.add(&mut ResourceDef::new("/profile"), None); user_map.add(&mut ResourceDef::new("/article/{id}"), None); user_map.add(&mut ResourceDef::new("/post/{post_id}"), None); user_map.add( &mut ResourceDef::new("/post/{post_id}/comment/{comment_id}"), None, ); root.add( &mut ResourceDef::root_prefix("/user/{id}"), Some(Rc::new(user_map)), ); let root = Rc::new(root); ResourceMap::finish(&root); // check root has no parent assert!(root.parent.borrow().upgrade().is_none()); // check child has parent reference assert!(root.nodes.as_ref().unwrap()[0] .parent .borrow() .upgrade() .is_some()); // check child's parent root id matches root's root id assert!(Rc::ptr_eq( &root.nodes.as_ref().unwrap()[0] .parent .borrow() .upgrade() .unwrap(), &root )); let output = format!("{:?}", root); assert!(output.starts_with("ResourceMap {")); assert!(output.ends_with(" }")); } #[test] fn short_circuit() { let mut root = ResourceMap::new(ResourceDef::prefix("")); let mut user_root = ResourceDef::prefix("/user"); let mut user_map = ResourceMap::new(user_root.clone()); user_map.add(&mut ResourceDef::new("/u1"), None); user_map.add(&mut ResourceDef::new("/u2"), None); root.add(&mut ResourceDef::new("/user/u3"), None); root.add(&mut user_root, Some(Rc::new(user_map))); root.add(&mut ResourceDef::new("/user/u4"), None); let rmap = Rc::new(root); ResourceMap::finish(&rmap); assert!(rmap.has_resource("/user/u1")); assert!(rmap.has_resource("/user/u2")); assert!(rmap.has_resource("/user/u3")); assert!(!rmap.has_resource("/user/u4")); } #[test] fn url_for() { let mut root = ResourceMap::new(ResourceDef::prefix("")); let mut user_scope_rdef = ResourceDef::prefix("/user"); let mut user_scope_map = ResourceMap::new(user_scope_rdef.clone()); let mut user_rdef = ResourceDef::new("/{user_id}"); let mut user_map = ResourceMap::new(user_rdef.clone()); let mut post_rdef = ResourceDef::new("/post/{sub_id}"); post_rdef.set_name("post"); user_map.add(&mut post_rdef, None); user_scope_map.add(&mut user_rdef, Some(Rc::new(user_map))); root.add(&mut user_scope_rdef, Some(Rc::new(user_scope_map))); let rmap = Rc::new(root); ResourceMap::finish(&rmap); let mut req = crate::test::TestRequest::default(); req.set_server_hostname("localhost:8888"); let req = req.to_http_request(); let url = rmap .url_for(&req, "post", ["u123", "foobar"]) .unwrap() .to_string(); assert_eq!(url, "http://localhost:8888/user/u123/post/foobar"); assert!(rmap.url_for(&req, "missing", ["u123"]).is_err()); } #[test] fn url_for_parser() { let mut root = ResourceMap::new(ResourceDef::prefix("")); let mut rdef_1 = ResourceDef::new("/{var}"); rdef_1.set_name("internal"); let mut rdef_2 = ResourceDef::new("http://host.dom/{var}"); rdef_2.set_name("external.1"); let mut rdef_3 = ResourceDef::new("{var}"); rdef_3.set_name("external.2"); root.add(&mut rdef_1, None); root.add(&mut rdef_2, None); root.add(&mut rdef_3, None); let rmap = Rc::new(root); ResourceMap::finish(&rmap); let mut req = crate::test::TestRequest::default(); req.set_server_hostname("localhost:8888"); let req = req.to_http_request(); const INPUT: &[&str] = &["a/../quick brown%20fox/%nan?query#frag"]; const OUTPUT: &str = "/quick%20brown%20fox/%nan%3Fquery%23frag"; let url = rmap.url_for(&req, "internal", INPUT).unwrap(); assert_eq!(url.path(), OUTPUT); let url = rmap.url_for(&req, "external.1", INPUT).unwrap(); assert_eq!(url.path(), OUTPUT); assert!(rmap.url_for(&req, "external.2", INPUT).is_err()); assert!(rmap.url_for(&req, "external.2", [""]).is_err()); } #[test] fn external_resource_with_no_name() { let mut root = ResourceMap::new(ResourceDef::prefix("")); let mut rdef = ResourceDef::new("https://duck.com/{query}"); root.add(&mut rdef, None); let rmap = Rc::new(root); ResourceMap::finish(&rmap); assert!(!rmap.has_resource("https://duck.com/abc")); } #[test] fn external_resource_with_name() { let mut root = ResourceMap::new(ResourceDef::prefix("")); let mut rdef = ResourceDef::new("https://duck.com/{query}"); rdef.set_name("duck"); root.add(&mut rdef, None); let rmap = Rc::new(root); ResourceMap::finish(&rmap); assert!(!rmap.has_resource("https://duck.com/abc")); let mut req = crate::test::TestRequest::default(); req.set_server_hostname("localhost:8888"); let req = req.to_http_request(); assert_eq!( rmap.url_for(&req, "duck", ["abcd"]).unwrap().to_string(), "https://duck.com/abcd" ); } #[test] fn url_for_override_within_map() { let mut root = ResourceMap::new(ResourceDef::prefix("")); let mut foo_rdef = ResourceDef::prefix("/foo"); let mut foo_map = ResourceMap::new(foo_rdef.clone()); let mut nested_rdef = ResourceDef::new("/nested"); nested_rdef.set_name("nested"); foo_map.add(&mut nested_rdef, None); root.add(&mut foo_rdef, Some(Rc::new(foo_map))); let mut foo_rdef = ResourceDef::prefix("/bar"); let mut foo_map = ResourceMap::new(foo_rdef.clone()); let mut nested_rdef = ResourceDef::new("/nested"); nested_rdef.set_name("nested"); foo_map.add(&mut nested_rdef, None); root.add(&mut foo_rdef, Some(Rc::new(foo_map))); let rmap = Rc::new(root); ResourceMap::finish(&rmap); let req = crate::test::TestRequest::default().to_http_request(); let url = rmap.url_for(&req, "nested", [""; 0]).unwrap().to_string(); assert_eq!(url, "http://localhost:8080/bar/nested"); assert!(rmap.url_for(&req, "missing", ["u123"]).is_err()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/web.rs
actix-web/src/web.rs
//! Essentials helper functions and types for application registration. //! //! # Request Extractors //! - [`Data`]: Application data item //! - [`ThinData`]: Cheap-to-clone application data item //! - [`ReqData`]: Request-local data item //! - [`Path`]: URL path parameters / dynamic segments //! - [`Query`]: URL query parameters //! - [`Header`]: Typed header //! - [`Json`]: JSON payload //! - [`Form`]: URL-encoded payload //! - [`Bytes`]: Raw payload //! //! # Responders //! - [`Json`]: JSON response //! - [`Form`]: URL-encoded response //! - [`Bytes`]: Raw bytes response //! - [`Redirect`](Redirect::to): Convenient redirect responses use std::{borrow::Cow, future::Future}; use actix_router::IntoPatterns; pub use bytes::{Buf, BufMut, Bytes, BytesMut}; pub use crate::{ config::ServiceConfig, data::Data, redirect::Redirect, request_data::ReqData, thin_data::ThinData, types::*, }; use crate::{ error::BlockingError, http::Method, service::WebService, FromRequest, Handler, Resource, Responder, Route, Scope, }; /// Creates a new resource for a specific path. /// /// Resources may have dynamic path segments. For example, a resource with the path `/a/{name}/c` /// would match all incoming requests with paths such as `/a/b/c`, `/a/1/c`, or `/a/etc/c`. /// /// A dynamic 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. This is done by looking /// up the identifier in the `Path` object returned by [`HttpRequest::match_info()`](crate::HttpRequest::match_info) method. /// /// By default, each segment matches the regular expression `[^{}/]+`. /// /// You can also specify a custom regex in the form `{identifier:regex}`: /// /// For instance, to route `GET`-requests on any route matching `/users/{userid}/{friend}` and store /// `userid` and `friend` in the exposed `Path` object: /// /// # Examples /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// let app = App::new().service( /// web::resource("/users/{userid}/{friend}") /// .route(web::get().to(|| HttpResponse::Ok())) /// .route(web::head().to(|| HttpResponse::MethodNotAllowed())) /// ); /// ``` pub fn resource<T: IntoPatterns>(path: T) -> Resource { Resource::new(path) } /// Creates scope for common path prefix. /// /// Scopes collect multiple paths under a common path prefix. The scope's path can contain dynamic /// path segments. /// /// # Avoid Trailing Slashes /// Avoid using trailing slashes in the scope prefix (e.g., `web::scope("/scope/")`). It will almost /// certainly not have the expected behavior. See the [documentation on resource definitions][pat] /// to understand why this is the case and how to correctly construct scope/prefix definitions. /// /// # Examples /// In this example, three routes are set up (and will handle any method): /// - `/{project_id}/path1` /// - `/{project_id}/path2` /// - `/{project_id}/path3` /// /// # Examples /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// let app = App::new().service( /// web::scope("/{project_id}") /// .service(web::resource("/path1").to(|| HttpResponse::Ok())) /// .service(web::resource("/path2").to(|| HttpResponse::Ok())) /// .service(web::resource("/path3").to(|| HttpResponse::MethodNotAllowed())) /// ); /// ``` /// /// [pat]: crate::dev::ResourceDef#prefix-resources pub fn scope(path: &str) -> Scope { Scope::new(path) } /// Creates a new un-configured route. pub fn route() -> Route { Route::new() } macro_rules! method_route { ($method_fn:ident, $method_const:ident) => { #[doc = concat!(" Creates a new route with `", stringify!($method_const), "` method guard.")] /// /// # Examples #[doc = concat!(" In this example, one `", stringify!($method_const), " /{project_id}` route is set up:")] /// ``` /// use actix_web::{web, App, HttpResponse}; /// /// let app = App::new().service( /// web::resource("/{project_id}") #[doc = concat!(" .route(web::", stringify!($method_fn), "().to(|| HttpResponse::Ok()))")] /// /// ); /// ``` pub fn $method_fn() -> Route { method(Method::$method_const) } }; } method_route!(get, GET); method_route!(post, POST); method_route!(put, PUT); method_route!(patch, PATCH); method_route!(delete, DELETE); method_route!(head, HEAD); method_route!(trace, TRACE); /// Creates a new route with specified method guard. /// /// # Examples /// In this example, one `GET /{project_id}` route is set up: /// /// ``` /// use actix_web::{web, http, App, HttpResponse}; /// /// let app = App::new().service( /// web::resource("/{project_id}") /// .route(web::method(http::Method::GET).to(|| HttpResponse::Ok())) /// ); /// ``` pub fn method(method: Method) -> Route { Route::new().method(method) } /// Creates a new any-method route with handler. /// /// ``` /// use actix_web::{web, App, HttpResponse, Responder}; /// /// async fn index() -> impl Responder { /// HttpResponse::Ok() /// } /// /// App::new().service( /// web::resource("/").route( /// web::to(index)) /// ); /// ``` pub fn to<F, Args>(handler: F) -> Route where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static, { Route::new().to(handler) } /// Creates a raw service for a specific path. /// /// ``` /// use actix_web::{dev, web, guard, App, Error, HttpResponse}; /// /// async fn my_service(req: dev::ServiceRequest) -> Result<dev::ServiceResponse, Error> { /// Ok(req.into_response(HttpResponse::Ok().finish())) /// } /// /// let app = App::new().service( /// web::service("/users/*") /// .guard(guard::Header("content-type", "text/plain")) /// .finish(my_service) /// ); /// ``` pub fn service<T: IntoPatterns>(path: T) -> WebService { WebService::new(path) } /// Create a relative or absolute redirect. /// /// See [`Redirect`] docs for usage details. /// /// # Examples /// ``` /// use actix_web::{web, App}; /// /// let app = App::new() /// // the client will resolve this redirect to /api/to-path /// .service(web::redirect("/api/from-path", "to-path")); /// ``` pub fn redirect(from: impl Into<Cow<'static, str>>, to: impl Into<Cow<'static, str>>) -> Redirect { Redirect::new(from, to) } /// Executes blocking function on a thread pool, returns future that resolves to result of the /// function execution. pub fn block<F, R>(f: F) -> impl Future<Output = Result<R, BlockingError>> where F: FnOnce() -> R + Send + 'static, R: Send + 'static, { let fut = actix_rt::task::spawn_blocking(f); async { fut.await.map_err(|_| BlockingError) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/server.rs
actix-web/src/server.rs
use std::{ any::Any, cmp, fmt, future::Future, io, marker::PhantomData, net, sync::{Arc, Mutex}, time::Duration, }; #[cfg(feature = "__tls")] use actix_http::TlsAcceptorConfig; use actix_http::{body::MessageBody, Extensions, HttpService, KeepAlive, Request, Response}; use actix_server::{Server, ServerBuilder}; use actix_service::{ map_config, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _, }; #[cfg(feature = "openssl")] use actix_tls::accept::openssl::reexports::{AlpnError, SslAcceptor, SslAcceptorBuilder}; use crate::{config::AppConfig, Error}; struct Socket { scheme: &'static str, addr: net::SocketAddr, } struct Config { host: Option<String>, keep_alive: KeepAlive, client_request_timeout: Duration, client_disconnect_timeout: Duration, h1_allow_half_closed: bool, #[allow(dead_code)] // only dead when no TLS features are enabled tls_handshake_timeout: Option<Duration>, } /// An HTTP Server. /// /// Create new HTTP server with application factory. /// /// # Automatic HTTP Version Selection /// /// There are two ways to select the HTTP version of an incoming connection: /// /// - One is to rely on the ALPN information that is provided when using a TLS (HTTPS); both /// versions are supported automatically when using either of the `.bind_rustls()` or /// `.bind_openssl()` methods. /// - The other is to read the first few bytes of the TCP stream. This is the only viable approach /// for supporting H2C, which allows the HTTP/2 protocol to work over plaintext connections. Use /// the `.bind_auto_h2c()` method to enable this behavior. /// /// # Examples /// /// ```no_run /// use actix_web::{web, App, HttpResponse, HttpServer}; /// /// #[actix_web::main] /// async fn main() -> std::io::Result<()> { /// HttpServer::new(|| { /// App::new() /// .service(web::resource("/").to(|| async { "hello world" })) /// }) /// .bind(("127.0.0.1", 8080))? /// .run() /// .await /// } /// ``` #[must_use] pub struct HttpServer<F, I, S, B> where F: Fn() -> I + Send + Clone + 'static, I: IntoServiceFactory<S, Request>, S: ServiceFactory<Request, Config = AppConfig>, S::Error: Into<Error>, S::InitError: fmt::Debug, S::Response: Into<Response<B>>, B: MessageBody, { pub(super) factory: F, config: Arc<Mutex<Config>>, backlog: u32, sockets: Vec<Socket>, builder: ServerBuilder, #[allow(clippy::type_complexity)] on_connect_fn: Option<Arc<dyn Fn(&dyn Any, &mut Extensions) + Send + Sync>>, _phantom: PhantomData<(S, B)>, } impl<F, I, S, B> HttpServer<F, I, S, B> where F: Fn() -> I + Send + Clone + 'static, I: IntoServiceFactory<S, Request>, S: ServiceFactory<Request, Config = AppConfig> + 'static, S::Error: Into<Error> + 'static, S::InitError: fmt::Debug, S::Response: Into<Response<B>> + 'static, <S::Service as Service<Request>>::Future: 'static, S::Service: 'static, B: MessageBody + 'static, { /// Create new HTTP server with application factory /// /// # Worker Count /// /// The `factory` will be instantiated multiple times in most configurations. See /// [`bind()`](Self::bind()) docs for more on how worker count and bind address resolution /// causes multiple server factory instantiations. pub fn new(factory: F) -> Self { HttpServer { factory, config: Arc::new(Mutex::new(Config { host: None, keep_alive: KeepAlive::default(), client_request_timeout: Duration::from_secs(5), client_disconnect_timeout: Duration::from_secs(1), h1_allow_half_closed: true, tls_handshake_timeout: None, })), backlog: 1024, sockets: Vec::new(), builder: ServerBuilder::default(), on_connect_fn: None, _phantom: PhantomData, } } /// Sets number of workers to start (per bind address). /// /// The default worker count is the determined by [`std::thread::available_parallelism()`]. See /// its documentation to determine what behavior you should expect when server is run. /// /// Note that the server factory passed to [`new`](Self::new()) will be instantiated **at least /// once per worker**. See [`bind()`](Self::bind()) docs for more on how worker count and bind /// address resolution causes multiple server factory instantiations. /// /// `num` must be greater than 0. /// /// # Panics /// /// Panics if `num` is 0. pub fn workers(mut self, num: usize) -> Self { self.builder = self.builder.workers(num); self } /// Sets server keep-alive preference. /// /// By default keep-alive is set to 5 seconds. pub fn keep_alive<T: Into<KeepAlive>>(self, val: T) -> Self { self.config.lock().unwrap().keep_alive = val.into(); self } /// Sets the maximum number of pending connections. /// /// This refers to the number of clients that can be waiting to be served. Exceeding this number /// results in the client getting an error when attempting to connect. It should only affect /// servers under significant load. /// /// Generally set in the 64–2048 range. Default value is 2048. /// /// This method will have no effect if called after a `bind()`. pub fn backlog(mut self, backlog: u32) -> Self { self.backlog = backlog; self.builder = self.builder.backlog(backlog); self } /// Sets the per-worker maximum number of concurrent connections. /// /// All socket listeners will stop accepting connections when this limit is reached for /// each worker. /// /// By default max connections is set to a 25k. pub fn max_connections(mut self, num: usize) -> Self { self.builder = self.builder.max_concurrent_connections(num); self } /// Sets the per-worker maximum concurrent TLS connection limit. /// /// All listeners will stop accepting connections when this limit is reached. It can be used to /// limit the global TLS CPU usage. /// /// By default max connections is set to a 256. #[allow(unused_variables)] pub fn max_connection_rate(self, num: usize) -> Self { #[cfg(feature = "__tls")] actix_tls::accept::max_concurrent_tls_connect(num); self } /// Sets max number of threads for each worker's blocking task thread pool. /// /// One thread pool is set up **per worker**; not shared across workers. /// /// By default, set to 512 divided by [available parallelism](std::thread::available_parallelism()). pub fn worker_max_blocking_threads(mut self, num: usize) -> Self { self.builder = self.builder.worker_max_blocking_threads(num); self } /// Sets server client timeout for first request. /// /// Defines a timeout for reading client request head. If a client does not transmit the entire /// set headers within this time, the request is terminated with a 408 (Request Timeout) error. /// /// To disable timeout set value to 0. /// /// By default client timeout is set to 5000 milliseconds. pub fn client_request_timeout(self, dur: Duration) -> Self { self.config.lock().unwrap().client_request_timeout = dur; self } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `client_request_timeout`.")] pub fn client_timeout(self, dur: Duration) -> Self { self.client_request_timeout(dur) } /// Sets server connection shutdown timeout. /// /// Defines a timeout for connection shutdown. If a shutdown procedure does not complete within /// this time, the request is dropped. /// /// To disable timeout set value to 0. /// /// By default client timeout is set to 5000 milliseconds. pub fn client_disconnect_timeout(self, dur: Duration) -> Self { self.config.lock().unwrap().client_disconnect_timeout = dur; self } /// Sets TLS handshake timeout. /// /// Defines a timeout for TLS handshake. If the TLS handshake does not complete within this /// time, the connection is closed. /// /// By default, the handshake timeout is 3 seconds. #[cfg(feature = "__tls")] pub fn tls_handshake_timeout(self, dur: Duration) -> Self { self.config .lock() .unwrap() .tls_handshake_timeout .replace(dur); self } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `client_disconnect_timeout`.")] pub fn client_shutdown(self, dur: u64) -> Self { self.client_disconnect_timeout(Duration::from_millis(dur)) } /// Sets whether HTTP/1 connections should support half-closures. /// /// Clients can choose to shutdown their writer-side of the connection after completing their /// request and while waiting for the server response. Setting this to `false` will cause the /// server to abort the connection handling as soon as it detects an EOF from the client. /// /// The default behavior is to allow, i.e. `true` pub fn h1_allow_half_closed(self, allow: bool) -> Self { self.config.lock().unwrap().h1_allow_half_closed = allow; self } /// Sets function that will be called once before each connection is handled. /// /// It will receive a `&std::any::Any`, which contains underlying connection type and an /// [Extensions] container so that connection data can be accessed in middleware and handlers. /// /// # Connection Types /// - `actix_tls::accept::openssl::TlsStream<actix_web::rt::net::TcpStream>` when using OpenSSL. /// - `actix_tls::accept::rustls_0_20::TlsStream<actix_web::rt::net::TcpStream>` when using /// Rustls v0.20. /// - `actix_tls::accept::rustls_0_21::TlsStream<actix_web::rt::net::TcpStream>` when using /// Rustls v0.21. /// - `actix_tls::accept::rustls_0_22::TlsStream<actix_web::rt::net::TcpStream>` when using /// Rustls v0.22. /// - `actix_tls::accept::rustls_0_23::TlsStream<actix_web::rt::net::TcpStream>` when using /// Rustls v0.23. /// - `actix_web::rt::net::TcpStream` when no encryption is used. /// /// See the `on_connect` example for additional details. pub fn on_connect<CB>(mut self, f: CB) -> HttpServer<F, I, S, B> where CB: Fn(&dyn Any, &mut Extensions) + Send + Sync + 'static, { self.on_connect_fn = Some(Arc::new(f)); self } /// Sets server host name. /// /// Host name is used by application router as a hostname for url generation. Check /// [`ConnectionInfo`](crate::dev::ConnectionInfo::host()) docs for more info. /// /// By default, hostname is set to "localhost". pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self { self.config.lock().unwrap().host = Some(val.as_ref().to_owned()); self } /// Flags the `System` to exit after server shutdown. /// /// Does nothing when running under `#[tokio::main]` runtime. pub fn system_exit(mut self) -> Self { self.builder = self.builder.system_exit(); self } /// Disables signal handling. pub fn disable_signals(mut self) -> Self { self.builder = self.builder.disable_signals(); self } /// Specify shutdown signal from a future. /// /// Using this method will prevent OS signal handlers being set up. /// /// Typically, a `CancellationToken` will be used, but any future _can_ be. /// /// # Examples /// /// ```no_run /// use actix_web::{App, HttpServer}; /// use tokio_util::sync::CancellationToken; /// /// # #[actix_web::main] /// # async fn main() -> std::io::Result<()> { /// let stop_signal = CancellationToken::new(); /// /// HttpServer::new(move || App::new()) /// .shutdown_signal(stop_signal.cancelled_owned()) /// .bind(("127.0.0.1", 8080))? /// .run() /// .await /// # } /// ``` pub fn shutdown_signal<Fut>(mut self, shutdown_signal: Fut) -> Self where Fut: Future<Output = ()> + Send + 'static, { self.builder = self.builder.shutdown_signal(shutdown_signal); self } /// Sets timeout for graceful worker shutdown of workers. /// /// After receiving a stop signal, workers have this much time to finish serving requests. /// Workers still alive after the timeout are force dropped. /// /// By default shutdown timeout sets to 30 seconds. pub fn shutdown_timeout(mut self, sec: u64) -> Self { self.builder = self.builder.shutdown_timeout(sec); self } /// Returns addresses of bound sockets. pub fn addrs(&self) -> Vec<net::SocketAddr> { self.sockets.iter().map(|s| s.addr).collect() } /// Returns addresses of bound sockets and the scheme for it. /// /// This is useful when the server is bound from different sources with some sockets listening /// on HTTP and some listening on HTTPS and the user should be presented with an enumeration of /// which socket requires which protocol. pub fn addrs_with_scheme(&self) -> Vec<(net::SocketAddr, &str)> { self.sockets.iter().map(|s| (s.addr, s.scheme)).collect() } /// Resolves socket address(es) and binds server to created listener(s). /// /// # Hostname Resolution /// /// When `addrs` includes a hostname, it is possible for this method to bind to both the IPv4 /// and IPv6 addresses that result from a DNS lookup. You can test this by passing /// `localhost:8080` and noting that the server binds to `127.0.0.1:8080` _and_ `[::1]:8080`. To /// bind additional addresses, call this method multiple times. /// /// Note that, if a DNS lookup is required, resolving hostnames is a blocking operation. /// /// # Worker Count /// /// The `factory` will be instantiated multiple times in most scenarios. The number of /// instantiations is number of [`workers`](Self::workers()) × number of sockets resolved by /// `addrs`. /// /// For example, if you've manually set [`workers`](Self::workers()) to 2, and use `127.0.0.1` /// as the bind `addrs`, then `factory` will be instantiated twice. However, using `localhost` /// as the bind `addrs` can often resolve to both `127.0.0.1` (IPv4) _and_ `::1` (IPv6), causing /// the `factory` to be instantiated 4 times (2 workers × 2 bind addresses). /// /// Using a bind address of `0.0.0.0`, which signals to use all interfaces, may also multiple /// the number of instantiations in a similar way. /// /// # Typical Usage /// /// In general, use `127.0.0.1:<port>` when testing locally and `0.0.0.0:<port>` when deploying /// (with or without a reverse proxy or load balancer) so that the server is accessible. /// /// # Errors /// /// Returns an `io::Error` if: /// - `addrs` cannot be resolved into one or more socket addresses; /// - all the resolved socket addresses are already bound. /// /// # Example /// /// ``` /// # use actix_web::{App, HttpServer}; /// # fn inner() -> std::io::Result<()> { /// HttpServer::new(|| App::new()) /// .bind(("127.0.0.1", 8080))? /// .bind("[::1]:9000")? /// # ; Ok(()) } /// ``` pub fn bind<A: net::ToSocketAddrs>(mut self, addrs: A) -> io::Result<Self> { let sockets = bind_addrs(addrs, self.backlog)?; for lst in sockets { self = self.listen(lst)?; } Ok(self) } /// Resolves socket address(es) and binds server to created listener(s) for plaintext HTTP/1.x /// or HTTP/2 connections. /// /// See [`bind()`](Self::bind()) for more details on `addrs` argument. #[cfg(feature = "http2")] pub fn bind_auto_h2c<A: net::ToSocketAddrs>(mut self, addrs: A) -> io::Result<Self> { let sockets = bind_addrs(addrs, self.backlog)?; for lst in sockets { self = self.listen_auto_h2c(lst)?; } Ok(self) } /// Resolves socket address(es) and binds server to created listener(s) for TLS connections /// using Rustls v0.20. /// /// See [`bind()`](Self::bind()) for more details on `addrs` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "rustls-0_20")] pub fn bind_rustls<A: net::ToSocketAddrs>( mut self, addrs: A, config: actix_tls::accept::rustls_0_20::reexports::ServerConfig, ) -> io::Result<Self> { let sockets = bind_addrs(addrs, self.backlog)?; for lst in sockets { self = self.listen_rustls_0_20_inner(lst, config.clone())?; } Ok(self) } /// Resolves socket address(es) and binds server to created listener(s) for TLS connections /// using Rustls v0.21. /// /// See [`bind()`](Self::bind()) for more details on `addrs` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "rustls-0_21")] pub fn bind_rustls_021<A: net::ToSocketAddrs>( mut self, addrs: A, config: actix_tls::accept::rustls_0_21::reexports::ServerConfig, ) -> io::Result<Self> { let sockets = bind_addrs(addrs, self.backlog)?; for lst in sockets { self = self.listen_rustls_0_21_inner(lst, config.clone())?; } Ok(self) } /// Resolves socket address(es) and binds server to created listener(s) for TLS connections /// using Rustls v0.22. /// /// See [`bind()`](Self::bind()) for more details on `addrs` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "rustls-0_22")] pub fn bind_rustls_0_22<A: net::ToSocketAddrs>( mut self, addrs: A, config: actix_tls::accept::rustls_0_22::reexports::ServerConfig, ) -> io::Result<Self> { let sockets = bind_addrs(addrs, self.backlog)?; for lst in sockets { self = self.listen_rustls_0_22_inner(lst, config.clone())?; } Ok(self) } /// Resolves socket address(es) and binds server to created listener(s) for TLS connections /// using Rustls v0.23. /// /// See [`bind()`](Self::bind()) for more details on `addrs` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "rustls-0_23")] pub fn bind_rustls_0_23<A: net::ToSocketAddrs>( mut self, addrs: A, config: actix_tls::accept::rustls_0_23::reexports::ServerConfig, ) -> io::Result<Self> { let sockets = bind_addrs(addrs, self.backlog)?; for lst in sockets { self = self.listen_rustls_0_23_inner(lst, config.clone())?; } Ok(self) } /// Resolves socket address(es) and binds server to created listener(s) for TLS connections /// using OpenSSL. /// /// See [`bind()`](Self::bind()) for more details on `addrs` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "openssl")] pub fn bind_openssl<A>(mut self, addrs: A, builder: SslAcceptorBuilder) -> io::Result<Self> where A: net::ToSocketAddrs, { let sockets = bind_addrs(addrs, self.backlog)?; let acceptor = openssl_acceptor(builder)?; for lst in sockets { self = self.listen_openssl_inner(lst, acceptor.clone())?; } Ok(self) } /// Binds to existing listener for accepting incoming connection requests. /// /// No changes are made to `lst`'s configuration. Ensure it is configured properly before /// passing ownership to `listen()`. pub fn listen(mut self, lst: net::TcpListener) -> io::Result<Self> { let cfg = Arc::clone(&self.config); let factory = self.factory.clone(); let addr = lst.local_addr().unwrap(); self.sockets.push(Socket { addr, scheme: "http", }); let on_connect_fn = self.on_connect_fn.clone(); self.builder = self.builder .listen(format!("actix-web-service-{}", addr), lst, move || { let cfg = cfg.lock().unwrap(); let host = cfg.host.clone().unwrap_or_else(|| format!("{}", addr)); let mut svc = HttpService::build() .keep_alive(cfg.keep_alive) .client_request_timeout(cfg.client_request_timeout) .client_disconnect_timeout(cfg.client_disconnect_timeout) .h1_allow_half_closed(cfg.h1_allow_half_closed) .local_addr(addr); if let Some(handler) = on_connect_fn.clone() { svc = svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext)) }; let fac = factory() .into_factory() .map_err(|err| err.into().error_response()); svc.finish(map_config(fac, move |_| { AppConfig::new(false, host.clone(), addr) })) .tcp() })?; Ok(self) } /// Binds to existing listener for accepting incoming plaintext HTTP/1.x or HTTP/2 connections. #[cfg(feature = "http2")] pub fn listen_auto_h2c(mut self, lst: net::TcpListener) -> io::Result<Self> { let cfg = Arc::clone(&self.config); let factory = self.factory.clone(); let addr = lst.local_addr().unwrap(); self.sockets.push(Socket { addr, scheme: "http", }); let on_connect_fn = self.on_connect_fn.clone(); self.builder = self.builder .listen(format!("actix-web-service-{}", addr), lst, move || { let cfg = cfg.lock().unwrap(); let host = cfg.host.clone().unwrap_or_else(|| format!("{}", addr)); let mut svc = HttpService::build() .keep_alive(cfg.keep_alive) .client_request_timeout(cfg.client_request_timeout) .client_disconnect_timeout(cfg.client_disconnect_timeout) .h1_allow_half_closed(cfg.h1_allow_half_closed) .local_addr(addr); if let Some(handler) = on_connect_fn.clone() { svc = svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext)) }; let fac = factory() .into_factory() .map_err(|err| err.into().error_response()); svc.finish(map_config(fac, move |_| { AppConfig::new(false, host.clone(), addr) })) .tcp_auto_h2c() })?; Ok(self) } /// Binds to existing listener for accepting incoming TLS connection requests using Rustls /// v0.20. /// /// See [`listen()`](Self::listen) for more details on the `lst` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "rustls-0_20")] pub fn listen_rustls( self, lst: net::TcpListener, config: actix_tls::accept::rustls_0_20::reexports::ServerConfig, ) -> io::Result<Self> { self.listen_rustls_0_20_inner(lst, config) } /// Binds to existing listener for accepting incoming TLS connection requests using Rustls /// v0.21. /// /// See [`listen()`](Self::listen()) for more details on the `lst` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "rustls-0_21")] pub fn listen_rustls_0_21( self, lst: net::TcpListener, config: actix_tls::accept::rustls_0_21::reexports::ServerConfig, ) -> io::Result<Self> { self.listen_rustls_0_21_inner(lst, config) } #[cfg(feature = "rustls-0_20")] fn listen_rustls_0_20_inner( mut self, lst: net::TcpListener, config: actix_tls::accept::rustls_0_20::reexports::ServerConfig, ) -> io::Result<Self> { let factory = self.factory.clone(); let cfg = Arc::clone(&self.config); let addr = lst.local_addr().unwrap(); self.sockets.push(Socket { addr, scheme: "https", }); let on_connect_fn = self.on_connect_fn.clone(); self.builder = self.builder .listen(format!("actix-web-service-{}", addr), lst, move || { let c = cfg.lock().unwrap(); let host = c.host.clone().unwrap_or_else(|| format!("{}", addr)); let svc = HttpService::build() .keep_alive(c.keep_alive) .client_request_timeout(c.client_request_timeout) .h1_allow_half_closed(c.h1_allow_half_closed) .client_disconnect_timeout(c.client_disconnect_timeout); let svc = if let Some(handler) = on_connect_fn.clone() { svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext)) } else { svc }; let fac = factory() .into_factory() .map_err(|err| err.into().error_response()); let acceptor_config = match c.tls_handshake_timeout { Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur), None => TlsAcceptorConfig::default(), }; svc.finish(map_config(fac, move |_| { AppConfig::new(true, host.clone(), addr) })) .rustls_with_config(config.clone(), acceptor_config) })?; Ok(self) } #[cfg(feature = "rustls-0_21")] fn listen_rustls_0_21_inner( mut self, lst: net::TcpListener, config: actix_tls::accept::rustls_0_21::reexports::ServerConfig, ) -> io::Result<Self> { let factory = self.factory.clone(); let cfg = Arc::clone(&self.config); let addr = lst.local_addr().unwrap(); self.sockets.push(Socket { addr, scheme: "https", }); let on_connect_fn = self.on_connect_fn.clone(); self.builder = self.builder .listen(format!("actix-web-service-{}", addr), lst, move || { let c = cfg.lock().unwrap(); let host = c.host.clone().unwrap_or_else(|| format!("{}", addr)); let svc = HttpService::build() .keep_alive(c.keep_alive) .client_request_timeout(c.client_request_timeout) .h1_allow_half_closed(c.h1_allow_half_closed) .client_disconnect_timeout(c.client_disconnect_timeout); let svc = if let Some(handler) = on_connect_fn.clone() { svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext)) } else { svc }; let fac = factory() .into_factory() .map_err(|err| err.into().error_response()); let acceptor_config = match c.tls_handshake_timeout { Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur), None => TlsAcceptorConfig::default(), }; svc.finish(map_config(fac, move |_| { AppConfig::new(true, host.clone(), addr) })) .rustls_021_with_config(config.clone(), acceptor_config) })?; Ok(self) } /// Binds to existing listener for accepting incoming TLS connection requests using Rustls /// v0.22. /// /// See [`listen()`](Self::listen()) for more details on the `lst` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "rustls-0_22")] pub fn listen_rustls_0_22( self, lst: net::TcpListener, config: actix_tls::accept::rustls_0_22::reexports::ServerConfig, ) -> io::Result<Self> { self.listen_rustls_0_22_inner(lst, config) } #[cfg(feature = "rustls-0_22")] fn listen_rustls_0_22_inner( mut self, lst: net::TcpListener, config: actix_tls::accept::rustls_0_22::reexports::ServerConfig, ) -> io::Result<Self> { let factory = self.factory.clone(); let cfg = Arc::clone(&self.config); let addr = lst.local_addr().unwrap(); self.sockets.push(Socket { addr, scheme: "https", }); let on_connect_fn = self.on_connect_fn.clone(); self.builder = self.builder .listen(format!("actix-web-service-{}", addr), lst, move || { let c = cfg.lock().unwrap(); let host = c.host.clone().unwrap_or_else(|| format!("{}", addr)); let svc = HttpService::build() .keep_alive(c.keep_alive) .client_request_timeout(c.client_request_timeout) .h1_allow_half_closed(c.h1_allow_half_closed) .client_disconnect_timeout(c.client_disconnect_timeout); let svc = if let Some(handler) = on_connect_fn.clone() { svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext)) } else { svc }; let fac = factory() .into_factory() .map_err(|err| err.into().error_response()); let acceptor_config = match c.tls_handshake_timeout { Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur), None => TlsAcceptorConfig::default(), }; svc.finish(map_config(fac, move |_| { AppConfig::new(true, host.clone(), addr) })) .rustls_0_22_with_config(config.clone(), acceptor_config) })?; Ok(self) } /// Binds to existing listener for accepting incoming TLS connection requests using Rustls /// v0.23. /// /// See [`listen()`](Self::listen()) for more details on the `lst` argument. /// /// ALPN protocols "h2" and "http/1.1" are added to any configured ones. #[cfg(feature = "rustls-0_23")] pub fn listen_rustls_0_23( self, lst: net::TcpListener, config: actix_tls::accept::rustls_0_23::reexports::ServerConfig, ) -> io::Result<Self> { self.listen_rustls_0_23_inner(lst, config) } #[cfg(feature = "rustls-0_23")] fn listen_rustls_0_23_inner( mut self, lst: net::TcpListener, config: actix_tls::accept::rustls_0_23::reexports::ServerConfig, ) -> io::Result<Self> { let factory = self.factory.clone(); let cfg = Arc::clone(&self.config); let addr = lst.local_addr().unwrap(); self.sockets.push(Socket { addr, scheme: "https", }); let on_connect_fn = self.on_connect_fn.clone(); self.builder = self.builder .listen(format!("actix-web-service-{}", addr), lst, move || { let c = cfg.lock().unwrap(); let host = c.host.clone().unwrap_or_else(|| format!("{}", addr)); let svc = HttpService::build() .keep_alive(c.keep_alive) .client_request_timeout(c.client_request_timeout) .h1_allow_half_closed(c.h1_allow_half_closed)
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
true
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/extract.rs
actix-web/src/extract.rs
//! Request extractors use std::{ convert::Infallible, future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use actix_http::{Method, Uri}; use actix_utils::future::{ok, Ready}; use futures_core::ready; use pin_project_lite::pin_project; use crate::{dev::Payload, Error, HttpRequest}; /// A type that implements [`FromRequest`] is called an **extractor** and can extract data from /// the request. Some types that implement this trait are: [`Json`], [`Header`], and [`Path`]. /// /// Check out [`ServiceRequest::extract`](crate::dev::ServiceRequest::extract) if you want to /// leverage extractors when implementing middlewares. /// /// # Configuration /// An extractor can be customized by injecting the corresponding configuration with one of: /// - [`App::app_data()`][crate::App::app_data] /// - [`Scope::app_data()`][crate::Scope::app_data] /// - [`Resource::app_data()`][crate::Resource::app_data] /// /// Here are some built-in extractors and their corresponding configuration. /// Please refer to the respective documentation for details. /// /// | Extractor | Configuration | /// |-------------|-------------------| /// | [`Header`] | _None_ | /// | [`Path`] | [`PathConfig`] | /// | [`Json`] | [`JsonConfig`] | /// | [`Form`] | [`FormConfig`] | /// | [`Query`] | [`QueryConfig`] | /// | [`Bytes`] | [`PayloadConfig`] | /// | [`String`] | [`PayloadConfig`] | /// | [`Payload`] | [`PayloadConfig`] | /// /// # Implementing An Extractor /// To reduce duplicate code in handlers where extracting certain parts of a request has a common /// structure, you can implement `FromRequest` for your own types. /// /// Note that the request payload can only be consumed by one extractor. /// /// [`Header`]: crate::web::Header /// [`Json`]: crate::web::Json /// [`JsonConfig`]: crate::web::JsonConfig /// [`Form`]: crate::web::Form /// [`FormConfig`]: crate::web::FormConfig /// [`Path`]: crate::web::Path /// [`PathConfig`]: crate::web::PathConfig /// [`Query`]: crate::web::Query /// [`QueryConfig`]: crate::web::QueryConfig /// [`Payload`]: crate::web::Payload /// [`PayloadConfig`]: crate::web::PayloadConfig /// [`String`]: FromRequest#impl-FromRequest-for-String /// [`Bytes`]: crate::web::Bytes#impl-FromRequest /// [`Either`]: crate::web::Either #[doc(alias = "extract", alias = "extractor")] pub trait FromRequest: Sized { /// The associated error which can be returned. type Error: Into<Error>; /// Future that resolves to a `Self`. /// /// To use an async function or block, the futures must be boxed. The following snippet will be /// common when creating async/await extractors (that do not consume the body). /// /// ```ignore /// type Future = Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>; /// // or /// type Future = futures_util::future::LocalBoxFuture<'static, Result<Self, Self::Error>>; /// /// fn from_request(req: HttpRequest, ...) -> Self::Future { /// let req = req.clone(); /// Box::pin(async move { /// ... /// }) /// } /// ``` type Future: Future<Output = Result<Self, Self::Error>>; /// Create a `Self` from request parts asynchronously. fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future; /// Create a `Self` from request head asynchronously. /// /// This method is short for `T::from_request(req, &mut Payload::None)`. fn extract(req: &HttpRequest) -> Self::Future { Self::from_request(req, &mut Payload::None) } } /// Optionally extract from the request. /// /// If the inner `T::from_request` returns an error, handler will receive `None` instead. /// /// # Examples /// ``` /// use actix_web::{web, dev, App, Error, HttpRequest, FromRequest}; /// use actix_web::error::ErrorBadRequest; /// use futures_util::future::{ok, err, Ready}; /// use serde::Deserialize; /// use rand; /// /// #[derive(Debug, Deserialize)] /// struct Thing { /// name: String /// } /// /// impl FromRequest for Thing { /// type Error = Error; /// type Future = Ready<Result<Self, Self::Error>>; /// /// fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { /// if rand::random() { /// ok(Thing { name: "thingy".into() }) /// } else { /// err(ErrorBadRequest("no luck")) /// } /// /// } /// } /// /// /// extract `Thing` from request /// async fn index(supplied_thing: Option<Thing>) -> String { /// match supplied_thing { /// // Puns not intended /// Some(thing) => format!("Got something: {:?}", thing), /// None => format!("No thing!") /// } /// } /// /// let app = App::new().service( /// web::resource("/users/:first").route( /// web::post().to(index)) /// ); /// ``` impl<T> FromRequest for Option<T> where T: FromRequest, { type Error = Infallible; type Future = FromRequestOptFuture<T::Future>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { FromRequestOptFuture { fut: T::from_request(req, payload), } } } pin_project! { pub struct FromRequestOptFuture<Fut> { #[pin] fut: Fut, } } impl<Fut, T, E> Future for FromRequestOptFuture<Fut> where Fut: Future<Output = Result<T, E>>, E: Into<Error>, { type Output = Result<Option<T>, Infallible>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let res = ready!(this.fut.poll(cx)); match res { Ok(t) => Poll::Ready(Ok(Some(t))), Err(err) => { log::debug!("Error for Option<T> extractor: {}", err.into()); Poll::Ready(Ok(None)) } } } } /// Extract from the request, passing error type through to handler. /// /// If the inner `T::from_request` returns an error, allow handler to receive the error rather than /// immediately returning an error response. /// /// # Examples /// ``` /// use actix_web::{web, dev, App, Result, Error, HttpRequest, FromRequest}; /// use actix_web::error::ErrorBadRequest; /// use futures_util::future::{ok, err, Ready}; /// use serde::Deserialize; /// use rand; /// /// #[derive(Debug, Deserialize)] /// struct Thing { /// name: String /// } /// /// impl FromRequest for Thing { /// type Error = Error; /// type Future = Ready<Result<Thing, Error>>; /// /// fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { /// if rand::random() { /// ok(Thing { name: "thingy".into() }) /// } else { /// err(ErrorBadRequest("no luck")) /// } /// } /// } /// /// /// extract `Thing` from request /// async fn index(supplied_thing: Result<Thing>) -> String { /// match supplied_thing { /// Ok(thing) => format!("Got thing: {thing:?}"), /// Err(err) => format!("Error extracting thing: {err}"), /// } /// } /// /// let app = App::new().service( /// web::resource("/users/:first").route(web::post().to(index)) /// ); /// ``` impl<T, E> FromRequest for Result<T, E> where T: FromRequest, T::Error: Into<E>, { type Error = Infallible; type Future = FromRequestResFuture<T::Future, E>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { FromRequestResFuture { fut: T::from_request(req, payload), _phantom: PhantomData, } } } pin_project! { pub struct FromRequestResFuture<Fut, E> { #[pin] fut: Fut, _phantom: PhantomData<E>, } } impl<Fut, T, Ei, E> Future for FromRequestResFuture<Fut, E> where Fut: Future<Output = Result<T, Ei>>, Ei: Into<E>, { type Output = Result<Result<T, E>, Infallible>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let res = ready!(this.fut.poll(cx)); Poll::Ready(Ok(res.map_err(Into::into))) } } /// Extract the request's URI. /// /// # Examples /// ``` /// use actix_web::{http::Uri, web, App, Responder}; /// /// async fn handler(uri: Uri) -> impl Responder { /// format!("Requested path: {}", uri.path()) /// } /// /// let app = App::new().default_service(web::to(handler)); /// ``` impl FromRequest for Uri { type Error = Infallible; type Future = Ready<Result<Self, Self::Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ok(req.uri().clone()) } } /// Extract the request's method. /// /// # Examples /// ``` /// use actix_web::{http::Method, web, App, Responder}; /// /// async fn handler(method: Method) -> impl Responder { /// format!("Request method: {}", method) /// } /// /// let app = App::new().default_service(web::to(handler)); /// ``` impl FromRequest for Method { type Error = Infallible; type Future = Ready<Result<Self, Self::Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ok(req.method().clone()) } } #[doc(hidden)] #[allow(non_snake_case)] mod tuple_from_req { use super::*; macro_rules! tuple_from_req { ($fut: ident; $($T: ident),*) => { /// FromRequest implementation for tuple #[allow(unused_parens)] impl<$($T: FromRequest + 'static),+> FromRequest for ($($T,)+) { type Error = Error; type Future = $fut<$($T),+>; fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { $fut { $( $T: ExtractFuture::Future { fut: $T::from_request(req, payload) }, )+ } } } pin_project! { pub struct $fut<$($T: FromRequest),+> { $( #[pin] $T: ExtractFuture<$T::Future, $T>, )+ } } impl<$($T: FromRequest),+> Future for $fut<$($T),+> { type Output = Result<($($T,)+), Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.project(); let mut ready = true; $( match this.$T.as_mut().project() { ExtractProj::Future { fut } => match fut.poll(cx) { Poll::Ready(Ok(output)) => { let _ = this.$T.as_mut().project_replace(ExtractFuture::Done { output }); }, Poll::Ready(Err(err)) => return Poll::Ready(Err(err.into())), Poll::Pending => ready = false, }, ExtractProj::Done { .. } => {}, ExtractProj::Empty => unreachable!("FromRequest polled after finished"), } )+ if ready { Poll::Ready(Ok( ($( match this.$T.project_replace(ExtractFuture::Empty) { ExtractReplaceProj::Done { output } => output, _ => unreachable!("FromRequest polled after finished"), }, )+) )) } else { Poll::Pending } } } }; } pin_project! { #[project = ExtractProj] #[project_replace = ExtractReplaceProj] enum ExtractFuture<Fut, Res> { Future { #[pin] fut: Fut }, Done { output: Res, }, Empty } } impl FromRequest for () { type Error = Infallible; type Future = Ready<Result<Self, Self::Error>>; fn from_request(_: &HttpRequest, _: &mut Payload) -> Self::Future { ok(()) } } tuple_from_req! { TupleFromRequest1; A } tuple_from_req! { TupleFromRequest2; A, B } tuple_from_req! { TupleFromRequest3; A, B, C } tuple_from_req! { TupleFromRequest4; A, B, C, D } tuple_from_req! { TupleFromRequest5; A, B, C, D, E } tuple_from_req! { TupleFromRequest6; A, B, C, D, E, F } tuple_from_req! { TupleFromRequest7; A, B, C, D, E, F, G } tuple_from_req! { TupleFromRequest8; A, B, C, D, E, F, G, H } tuple_from_req! { TupleFromRequest9; A, B, C, D, E, F, G, H, I } tuple_from_req! { TupleFromRequest10; A, B, C, D, E, F, G, H, I, J } tuple_from_req! { TupleFromRequest11; A, B, C, D, E, F, G, H, I, J, K } tuple_from_req! { TupleFromRequest12; A, B, C, D, E, F, G, H, I, J, K, L } tuple_from_req! { TupleFromRequest13; A, B, C, D, E, F, G, H, I, J, K, L, M } tuple_from_req! { TupleFromRequest14; A, B, C, D, E, F, G, H, I, J, K, L, M, N } tuple_from_req! { TupleFromRequest15; A, B, C, D, E, F, G, H, I, J, K, L, M, N, O } tuple_from_req! { TupleFromRequest16; A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P } } #[cfg(test)] mod tests { use actix_http::header; use bytes::Bytes; use serde::Deserialize; use super::*; use crate::{ test::TestRequest, types::{Form, FormConfig}, }; #[derive(Deserialize, Debug, PartialEq)] struct Info { hello: String, } #[actix_rt::test] async fn test_option() { let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .data(FormConfig::default().limit(4096)) .to_http_parts(); let r = Option::<Form<Info>>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(r, None); let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, "9")) .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); let r = Option::<Form<Info>>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!( r, Some(Form(Info { hello: "world".into() })) ); let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, "9")) .set_payload(Bytes::from_static(b"bye=world")) .to_http_parts(); let r = Option::<Form<Info>>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(r, None); } #[actix_rt::test] async fn test_result() { let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, "11")) .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); let r = Result::<Form<Info>, Error>::from_request(&req, &mut pl) .await .unwrap() .unwrap(); assert_eq!( r, Form(Info { hello: "world".into() }) ); let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, 9)) .set_payload(Bytes::from_static(b"bye=world")) .to_http_parts(); struct MyError; impl From<Error> for MyError { fn from(_: Error) -> Self { Self } } let r = Result::<Form<Info>, MyError>::from_request(&req, &mut pl) .await .unwrap(); assert!(r.is_err()); } #[actix_rt::test] async fn test_uri() { let req = TestRequest::default().uri("/foo/bar").to_http_request(); let uri = Uri::extract(&req).await.unwrap(); assert_eq!(uri.path(), "/foo/bar"); } #[actix_rt::test] async fn test_method() { let req = TestRequest::default().method(Method::GET).to_http_request(); let method = Method::extract(&req).await.unwrap(); assert_eq!(method, Method::GET); } #[actix_rt::test] async fn test_concurrent() { let (req, mut pl) = TestRequest::default() .uri("/foo/bar") .method(Method::GET) .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((header::CONTENT_LENGTH, "11")) .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); let (method, uri, form) = <(Method, Uri, Form<Info>)>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(method, Method::GET); assert_eq!(uri.path(), "/foo/bar"); assert_eq!( form, Form(Info { hello: "world".into() }) ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/request.rs
actix-web/src/request.rs
use std::{ cell::{Ref, RefCell, RefMut}, fmt, net, rc::Rc, str, }; use actix_http::{Message, RequestHead}; use actix_router::{Path, Url}; use actix_utils::future::{ok, Ready}; #[cfg(feature = "cookies")] use cookie::{Cookie, ParseError as CookieParseError}; use smallvec::SmallVec; use crate::{ app_service::AppInitServiceState, config::AppConfig, dev::{Extensions, Payload}, error::UrlGenerationError, http::{header::HeaderMap, Method, Uri, Version}, info::ConnectionInfo, rmap::ResourceMap, Error, FromRequest, HttpMessage, }; #[cfg(feature = "cookies")] struct Cookies(Vec<Cookie<'static>>); /// An incoming request. #[derive(Clone)] pub struct HttpRequest { /// # Invariant /// `Rc<HttpRequestInner>` is used exclusively and NO `Weak<HttpRequestInner>` /// is allowed anywhere in the code. Weak pointer is purposely ignored when /// doing `Rc`'s ref counter check. Expect panics if this invariant is violated. pub(crate) inner: Rc<HttpRequestInner>, } pub(crate) struct HttpRequestInner { pub(crate) head: Message<RequestHead>, pub(crate) path: Path<Url>, pub(crate) app_data: SmallVec<[Rc<Extensions>; 4]>, pub(crate) conn_data: Option<Rc<Extensions>>, pub(crate) extensions: Rc<RefCell<Extensions>>, app_state: Rc<AppInitServiceState>, } impl HttpRequest { #[inline] pub(crate) fn new( path: Path<Url>, head: Message<RequestHead>, app_state: Rc<AppInitServiceState>, app_data: Rc<Extensions>, conn_data: Option<Rc<Extensions>>, extensions: Rc<RefCell<Extensions>>, ) -> HttpRequest { let mut data = SmallVec::<[Rc<Extensions>; 4]>::new(); data.push(app_data); HttpRequest { inner: Rc::new(HttpRequestInner { head, path, app_state, app_data: data, conn_data, extensions, }), } } } impl HttpRequest { /// This method returns reference to the request head #[inline] pub fn head(&self) -> &RequestHead { &self.inner.head } /// This method returns mutable reference to the request head. /// panics if multiple references of HTTP request exists. #[inline] pub(crate) fn head_mut(&mut self) -> &mut RequestHead { &mut Rc::get_mut(&mut self.inner).unwrap().head } /// Request's uri. #[inline] pub fn uri(&self) -> &Uri { &self.head().uri } /// Returns request's original full URL. /// /// Reconstructed URL is best-effort, using [`connection_info`](HttpRequest::connection_info()) /// to get forwarded scheme & host. /// /// ``` /// use actix_web::test::TestRequest; /// let req = TestRequest::with_uri("http://10.1.2.3:8443/api?id=4&name=foo") /// .insert_header(("host", "example.com")) /// .to_http_request(); /// /// assert_eq!( /// req.full_url().as_str(), /// "http://example.com/api?id=4&name=foo", /// ); /// ``` pub fn full_url(&self) -> url::Url { let info = self.connection_info(); let scheme = info.scheme(); let host = info.host(); let path_and_query = self .uri() .path_and_query() .map(|paq| paq.as_str()) .unwrap_or("/"); url::Url::parse(&format!("{scheme}://{host}{path_and_query}")).unwrap() } /// Read the Request method. #[inline] pub fn method(&self) -> &Method { &self.head().method } /// Read the Request Version. #[inline] pub fn version(&self) -> Version { self.head().version } #[inline] /// Returns request's headers. pub fn headers(&self) -> &HeaderMap { &self.head().headers } /// The target path of this request. #[inline] pub fn path(&self) -> &str { self.head().uri.path() } /// The query string in the URL. /// /// Example: `id=10` #[inline] pub fn query_string(&self) -> &str { self.uri().query().unwrap_or_default() } /// Returns a reference to the URL parameters container. /// /// A URL parameter is specified in the form `{identifier}`, where the identifier can be used /// later in a request handler to access the matched value for that parameter. /// /// # Percent Encoding and URL Parameters /// Because each URL parameter is able to capture multiple path segments, none of /// `["%2F", "%25", "%2B"]` found in the request URI are decoded into `["/", "%", "+"]` in order /// to preserve path integrity. If a URL parameter is expected to contain these characters, then /// it is on the user to decode them or use the [`web::Path`](crate::web::Path) extractor which /// _will_ decode these special sequences. #[inline] pub fn match_info(&self) -> &Path<Url> { &self.inner.path } /// Returns a mutable reference to the URL parameters container. /// /// # Panics /// Panics if this `HttpRequest` has been cloned. #[inline] pub(crate) fn match_info_mut(&mut self) -> &mut Path<Url> { &mut Rc::get_mut(&mut self.inner).unwrap().path } /// The resource definition pattern that matched the path. Useful for logging and metrics. /// /// For example, when a resource with pattern `/user/{id}/profile` is defined and a call is made /// to `/user/123/profile` this function would return `Some("/user/{id}/profile")`. /// /// Returns a None when no resource is fully matched, including default services. #[inline] pub fn match_pattern(&self) -> Option<String> { self.resource_map().match_pattern(self.path()) } /// The resource name that matched the path. Useful for logging and metrics. /// /// Returns a None when no resource is fully matched, including default services. #[inline] pub fn match_name(&self) -> Option<&str> { self.resource_map().match_name(self.path()) } /// Returns a reference a piece of connection data set in an [on-connect] callback. /// /// ```ignore /// let opt_t = req.conn_data::<PeerCertificate>(); /// ``` /// /// [on-connect]: crate::HttpServer::on_connect pub fn conn_data<T: 'static>(&self) -> Option<&T> { self.inner .conn_data .as_deref() .and_then(|container| container.get::<T>()) } /// Generates URL for a named resource. /// /// This substitutes in sequence all URL parameters that appear in the resource itself and in /// parent [scopes](crate::web::scope), if any. /// /// It is worth noting that the characters `['/', '%']` are not escaped and therefore a single /// URL parameter may expand into multiple path segments and `elements` can be percent-encoded /// beforehand without worrying about double encoding. Any other character that is not valid in /// a URL path context is escaped using percent-encoding. /// /// # Examples /// ``` /// # use actix_web::{web, App, HttpRequest, HttpResponse}; /// fn index(req: HttpRequest) -> HttpResponse { /// let url = req.url_for("foo", &["1", "2", "3"]); // <- generate URL for "foo" resource /// HttpResponse::Ok().into() /// } /// /// let app = App::new() /// .service(web::resource("/test/{one}/{two}/{three}") /// .name("foo") // <- set resource name so it can be used in `url_for` /// .route(web::get().to(|| HttpResponse::Ok())) /// ); /// ``` pub fn url_for<U, I>(&self, name: &str, elements: U) -> Result<url::Url, UrlGenerationError> where U: IntoIterator<Item = I>, I: AsRef<str>, { self.resource_map().url_for(self, name, elements) } /// 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::Url, UrlGenerationError> { const NO_PARAMS: [&str; 0] = []; self.url_for(name, NO_PARAMS) } /// Get a reference to a `ResourceMap` of current application. #[inline] pub fn resource_map(&self) -> &ResourceMap { self.app_state().rmap() } /// Returns peer socket address. /// /// Peer address is the directly connected peer's socket address. If a proxy is used in front of /// the Actix Web server, then it would be address of this proxy. /// /// For expanded client connection information, use [`connection_info`] instead. /// /// Will only return `None` when server is listening on [UDS socket] or when called in unit /// tests unless [`TestRequest::peer_addr`] is used. /// /// [UDS socket]: crate::HttpServer::bind_uds /// [`TestRequest::peer_addr`]: crate::test::TestRequest::peer_addr /// [`connection_info`]: Self::connection_info #[inline] pub fn peer_addr(&self) -> Option<net::SocketAddr> { self.head().peer_addr } /// Returns connection info for the current request. /// /// The return type, [`ConnectionInfo`], can also be used as an extractor. /// /// # Panics /// Panics if request's extensions container is already borrowed. #[inline] pub fn connection_info(&self) -> Ref<'_, ConnectionInfo> { if !self.extensions().contains::<ConnectionInfo>() { let info = ConnectionInfo::new(self.head(), self.app_config()); self.extensions_mut().insert(info); } Ref::map(self.extensions(), |data| data.get().unwrap()) } /// Returns a reference to the application's connection configuration. #[inline] pub fn app_config(&self) -> &AppConfig { self.app_state().config() } /// Retrieves a piece of application state. /// /// Extracts any object stored with [`App::app_data()`](crate::App::app_data) (or the /// counterpart methods on [`Scope`](crate::Scope::app_data) and /// [`Resource`](crate::Resource::app_data)) during application configuration. /// /// Since the Actix Web router layers application data, the returned object will reference the /// "closest" instance of the type. For example, if an `App` stores a `u32`, a nested `Scope` /// also stores a `u32`, and the delegated request handler falls within that `Scope`, then /// calling `.app_data::<u32>()` on an `HttpRequest` within that handler will return the /// `Scope`'s instance. However, using the same router set up and a request that does not get /// captured by the `Scope`, `.app_data::<u32>()` would return the `App`'s instance. /// /// If the state was stored using the [`Data`] wrapper, then it must also be retrieved using /// this same type. /// /// See also the [`Data`] extractor. /// /// # Examples /// ```no_run /// # use actix_web::{test::TestRequest, web::Data}; /// # let req = TestRequest::default().to_http_request(); /// # type T = u32; /// let opt_t: Option<&Data<T>> = req.app_data::<Data<T>>(); /// ``` /// /// [`Data`]: crate::web::Data #[doc(alias = "state")] pub fn app_data<T: 'static>(&self) -> Option<&T> { for container in self.inner.app_data.iter().rev() { if let Some(data) = container.get::<T>() { return Some(data); } } None } #[inline] fn app_state(&self) -> &AppInitServiceState { &self.inner.app_state } /// Load request cookies. #[cfg(feature = "cookies")] pub fn cookies(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> { use actix_http::header::COOKIE; if self.extensions().get::<Cookies>().is_none() { let mut cookies = Vec::new(); for hdr in self.headers().get_all(COOKIE) { let s = str::from_utf8(hdr.as_bytes()).map_err(CookieParseError::from)?; for cookie_str in s.split(';').map(|s| s.trim()) { if !cookie_str.is_empty() { cookies.push(Cookie::parse_encoded(cookie_str)?.into_owned()); } } } self.extensions_mut().insert(Cookies(cookies)); } Ok(Ref::map(self.extensions(), |ext| { &ext.get::<Cookies>().unwrap().0 })) } /// Return request cookie. #[cfg(feature = "cookies")] pub fn cookie(&self, name: &str) -> Option<Cookie<'static>> { if let Ok(cookies) = self.cookies() { for cookie in cookies.iter() { if cookie.name() == name { return Some(cookie.to_owned()); } } } None } } impl HttpMessage for HttpRequest { type Stream = (); #[inline] fn headers(&self) -> &HeaderMap { &self.head().headers } #[inline] fn extensions(&self) -> Ref<'_, Extensions> { self.inner.extensions.borrow() } #[inline] fn extensions_mut(&self) -> RefMut<'_, Extensions> { self.inner.extensions.borrow_mut() } #[inline] fn take_payload(&mut self) -> Payload<Self::Stream> { Payload::None } } impl Drop for HttpRequest { fn drop(&mut self) { // if possible, contribute to current worker's HttpRequest allocation pool // This relies on no weak references to inner existing anywhere within the codebase. if let Some(inner) = Rc::get_mut(&mut self.inner) { if inner.app_state.pool().is_available() { // clear additional app_data and keep the root one for reuse. inner.app_data.truncate(1); // Inner is borrowed mut here and; get req data mutably to reduce borrow check. Also // we know the req_data Rc will not have any clones at this point to unwrap is okay. Rc::get_mut(&mut inner.extensions) .unwrap() .get_mut() .clear(); // We can't use the same trick as req data because the conn_data is held by the // dispatcher, too. inner.conn_data = None; // a re-borrow of pool is necessary here. let req = Rc::clone(&self.inner); self.app_state().pool().push(req); } } } } /// It is possible to get `HttpRequest` as an extractor handler parameter /// /// # Examples /// ``` /// use actix_web::{web, App, HttpRequest}; /// use serde::Deserialize; /// /// /// extract `Thing` from request /// async fn index(req: HttpRequest) -> String { /// format!("Got thing: {:?}", req) /// } /// /// let app = App::new().service( /// web::resource("/users/{first}").route( /// web::get().to(index)) /// ); /// ``` impl FromRequest for HttpRequest { type Error = Error; type Future = Ready<Result<Self, Error>>; #[inline] fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ok(req.clone()) } } impl fmt::Debug for HttpRequest { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { writeln!( f, "\nHttpRequest {:?} {}:{}", self.inner.head.version, self.inner.head.method, self.path() )?; if !self.query_string().is_empty() { writeln!(f, " query: ?{:?}", self.query_string())?; } if !self.match_info().is_empty() { writeln!(f, " params: {:?}", self.match_info())?; } writeln!(f, " headers:")?; for (key, val) in self.headers().iter() { match key { // redact sensitive header values from debug output &crate::http::header::AUTHORIZATION | &crate::http::header::PROXY_AUTHORIZATION | &crate::http::header::COOKIE => writeln!(f, " {:?}: {:?}", key, "*redacted*")?, _ => writeln!(f, " {:?}: {:?}", key, val)?, } } Ok(()) } } /// Slab-allocated `HttpRequest` Pool /// /// Since request processing may yield for asynchronous events to complete, a worker may have many /// requests in-flight at any time. Pooling requests like this amortizes the performance and memory /// costs of allocating and de-allocating HttpRequest objects as frequently as they otherwise would. /// /// Request objects are added when they are dropped (see `<HttpRequest as Drop>::drop`) and re-used /// in `<AppInitService as Service>::call` when there are available objects in the list. /// /// The pool's default capacity is 128 items. pub(crate) struct HttpRequestPool { inner: RefCell<Vec<Rc<HttpRequestInner>>>, cap: usize, } impl Default for HttpRequestPool { fn default() -> Self { Self::with_capacity(128) } } impl HttpRequestPool { pub(crate) fn with_capacity(cap: usize) -> Self { HttpRequestPool { inner: RefCell::new(Vec::with_capacity(cap)), cap, } } /// Re-use a previously allocated (but now completed/discarded) HttpRequest object. #[inline] pub(crate) fn pop(&self) -> Option<HttpRequest> { self.inner .borrow_mut() .pop() .map(|inner| HttpRequest { inner }) } /// Check if the pool still has capacity for request storage. #[inline] pub(crate) fn is_available(&self) -> bool { self.inner.borrow_mut().len() < self.cap } /// Push a request to pool. #[inline] pub(crate) fn push(&self, req: Rc<HttpRequestInner>) { self.inner.borrow_mut().push(req); } /// Clears all allocated HttpRequest objects. pub(crate) fn clear(&self) { self.inner.borrow_mut().clear() } } #[cfg(test)] mod tests { use bytes::Bytes; use super::*; use crate::{ dev::{ResourceDef, Service}, http::{header, StatusCode}, test::{self, call_service, init_service, read_body, TestRequest}, web, App, HttpResponse, }; #[test] fn test_debug() { let req = TestRequest::default() .insert_header(("content-type", "text/plain")) .to_http_request(); let dbg = format!("{:?}", req); assert!(dbg.contains("HttpRequest")); } #[test] #[cfg(feature = "cookies")] fn test_no_request_cookies() { let req = TestRequest::default().to_http_request(); assert!(req.cookies().unwrap().is_empty()); } #[test] #[cfg(feature = "cookies")] fn test_request_cookies() { let req = TestRequest::default() .append_header((header::COOKIE, "cookie1=value1")) .append_header((header::COOKIE, "cookie2=value2")) .to_http_request(); { 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() { let req = TestRequest::with_uri("/?id=test").to_http_request(); assert_eq!(req.query_string(), "id=test"); } #[test] fn test_url_for() { let mut res = ResourceDef::new("/user/{name}.{ext}"); res.set_name("index"); let mut rmap = ResourceMap::new(ResourceDef::prefix("")); rmap.add(&mut res, None); assert!(rmap.has_resource("/user/test.html")); assert!(!rmap.has_resource("/test/unknown")); let req = TestRequest::default() .insert_header((header::HOST, "www.rust-lang.org")) .rmap(rmap) .to_http_request(); 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_static() { let mut rdef = ResourceDef::new("/index.html"); rdef.set_name("index"); let mut rmap = ResourceMap::new(ResourceDef::prefix("")); rmap.add(&mut rdef, None); assert!(rmap.has_resource("/index.html")); let req = TestRequest::with_uri("/test") .insert_header((header::HOST, "www.rust-lang.org")) .rmap(rmap) .to_http_request(); let url = req.url_for_static("index"); assert_eq!( url.ok().unwrap().as_str(), "http://www.rust-lang.org/index.html" ); } #[test] fn test_match_name() { let mut rdef = ResourceDef::new("/index.html"); rdef.set_name("index"); let mut rmap = ResourceMap::new(ResourceDef::prefix("")); rmap.add(&mut rdef, None); assert!(rmap.has_resource("/index.html")); let req = TestRequest::default() .uri("/index.html") .rmap(rmap) .to_http_request(); assert_eq!(req.match_name(), Some("index")); } #[test] fn test_url_for_external() { let mut rdef = ResourceDef::new("https://youtube.com/watch/{video_id}"); rdef.set_name("youtube"); let mut rmap = ResourceMap::new(ResourceDef::prefix("")); rmap.add(&mut rdef, None); let req = TestRequest::default().rmap(rmap).to_http_request(); let url = req.url_for("youtube", ["oHg5SJYRHA0"]); assert_eq!( url.ok().unwrap().as_str(), "https://youtube.com/watch/oHg5SJYRHA0" ); } #[actix_rt::test] async fn test_drop_http_request_pool() { let srv = init_service( App::new().service(web::resource("/").to(|req: HttpRequest| { HttpResponse::Ok() .insert_header(("pool_cap", req.app_state().pool().cap)) .finish() })), ) .await; let req = TestRequest::default().to_request(); let resp = call_service(&srv, req).await; drop(srv); assert_eq!(resp.headers().get("pool_cap").unwrap(), "128"); } #[actix_rt::test] async fn test_data() { let srv = init_service(App::new().app_data(10usize).service(web::resource("/").to( |req: HttpRequest| { if req.app_data::<usize>().is_some() { HttpResponse::Ok() } else { HttpResponse::BadRequest() } }, ))) .await; let req = TestRequest::default().to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let srv = init_service(App::new().app_data(10u32).service(web::resource("/").to( |req: HttpRequest| { if req.app_data::<usize>().is_some() { HttpResponse::Ok() } else { HttpResponse::BadRequest() } }, ))) .await; let req = TestRequest::default().to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } #[actix_rt::test] async fn test_cascading_data() { #[allow(dead_code)] fn echo_usize(req: HttpRequest) -> HttpResponse { let num = req.app_data::<usize>().unwrap(); HttpResponse::Ok().body(num.to_string()) } let srv = init_service( App::new() .app_data(88usize) .service(web::resource("/").route(web::get().to(echo_usize))) .service( web::resource("/one") .app_data(1u32) .route(web::get().to(echo_usize)), ), ) .await; let req = TestRequest::get().uri("/").to_request(); let resp = srv.call(req).await.unwrap(); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"88")); let req = TestRequest::get().uri("/one").to_request(); let resp = srv.call(req).await.unwrap(); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"88")); } #[actix_rt::test] async fn test_overwrite_data() { #[allow(dead_code)] fn echo_usize(req: HttpRequest) -> HttpResponse { let num = req.app_data::<usize>().unwrap(); HttpResponse::Ok().body(num.to_string()) } let srv = init_service( App::new() .app_data(88usize) .service(web::resource("/").route(web::get().to(echo_usize))) .service( web::resource("/one") .app_data(1usize) .route(web::get().to(echo_usize)), ), ) .await; let req = TestRequest::get().uri("/").to_request(); let resp = srv.call(req).await.unwrap(); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"88")); let req = TestRequest::get().uri("/one").to_request(); let resp = srv.call(req).await.unwrap(); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"1")); } #[actix_rt::test] async fn test_app_data_dropped() { struct Tracker { pub dropped: bool, } struct Foo { tracker: Rc<RefCell<Tracker>>, } impl Drop for Foo { fn drop(&mut self) { self.tracker.borrow_mut().dropped = true; } } let tracker = Rc::new(RefCell::new(Tracker { dropped: false })); { let tracker2 = Rc::clone(&tracker); let srv = init_service(App::new().service(web::resource("/").to( move |req: HttpRequest| { req.extensions_mut().insert(Foo { tracker: Rc::clone(&tracker2), }); HttpResponse::Ok() }, ))) .await; let req = TestRequest::default().to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } assert!(tracker.borrow().dropped); } #[actix_rt::test] async fn extract_path_pattern() { let srv = init_service( App::new().service( web::scope("/user/{id}") .service(web::resource("/profile").route(web::get().to( move |req: HttpRequest| { assert_eq!(req.match_pattern(), Some("/user/{id}/profile".to_owned())); HttpResponse::Ok().finish() }, ))) .default_service(web::to(move |req: HttpRequest| { assert!(req.match_pattern().is_none()); HttpResponse::Ok().finish() })), ), ) .await; let req = TestRequest::get().uri("/user/22/profile").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let req = TestRequest::get().uri("/user/22/not-exist").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); } #[actix_rt::test] async fn extract_path_pattern_complex() { let srv = init_service( App::new() .service(web::scope("/user").service(web::scope("/{id}").service( web::resource("").to(move |req: HttpRequest| { assert_eq!(req.match_pattern(), Some("/user/{id}".to_owned())); HttpResponse::Ok().finish() }), ))) .service(web::resource("/").to(move |req: HttpRequest| { assert_eq!(req.match_pattern(), Some("/".to_owned())); HttpResponse::Ok().finish() })) .default_service(web::to(move |req: HttpRequest| { assert!(req.match_pattern().is_none()); HttpResponse::Ok().finish() })), ) .await; let req = TestRequest::get().uri("/user/test").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let req = TestRequest::get().uri("/").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let req = TestRequest::get().uri("/not-exist").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); } #[actix_rt::test] async fn url_for_closest_named_resource() { // we mount the route named 'nested' on 2 different scopes, 'a' and 'b' let srv = test::init_service( App::new() .service( web::scope("/foo") .service(web::resource("/nested").name("nested").route(web::get().to( |req: HttpRequest| { HttpResponse::Ok() .body(format!("{}", req.url_for_static("nested").unwrap())) }, ))) .service(web::scope("/baz").service(web::resource("deep"))) .service(web::resource("{foo_param}")), ) .service(web::scope("/bar").service( web::resource("/nested").name("nested").route(web::get().to( |req: HttpRequest| { HttpResponse::Ok() .body(format!("{}", req.url_for_static("nested").unwrap())) }, )), )), ) .await; let foo_resp = test::call_service(&srv, TestRequest::with_uri("/foo/nested").to_request()).await; assert_eq!(foo_resp.status(), StatusCode::OK); let body = read_body(foo_resp).await; // `body` equals http://localhost:8080/bar/nested // because nested from /bar overrides /foo's // to do this any other way would require something like a custom tree search // see https://github.com/actix/actix-web/issues/1763 assert_eq!(body, "http://localhost:8080/bar/nested"); let bar_resp = test::call_service(&srv, TestRequest::with_uri("/bar/nested").to_request()).await; assert_eq!(bar_resp.status(), StatusCode::OK); let body = read_body(bar_resp).await; assert_eq!(body, "http://localhost:8080/bar/nested"); } #[test] fn authorization_header_hidden_in_debug() { let authorization_header = "Basic bXkgdXNlcm5hbWU6bXkgcGFzc3dvcmQK"; let req = TestRequest::get() .insert_header((crate::http::header::AUTHORIZATION, authorization_header)) .to_http_request(); assert!(!format!("{:?}", req).contains(authorization_header)); } #[test] fn proxy_authorization_header_hidden_in_debug() { let proxy_authorization_header = "secret value"; let req = TestRequest::get() .insert_header(( crate::http::header::PROXY_AUTHORIZATION, proxy_authorization_header, )) .to_http_request(); assert!(!format!("{:?}", req).contains(proxy_authorization_header)); } #[test] fn cookie_header_hidden_in_debug() { let cookie_header = "secret"; let req = TestRequest::get() .insert_header((crate::http::header::COOKIE, cookie_header))
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
true
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/route.rs
actix-web/src/route.rs
use std::{mem, rc::Rc}; use actix_http::{body::MessageBody, Method}; use actix_service::{ apply, boxed::{self, BoxService}, fn_service, Service, ServiceFactory, ServiceFactoryExt, Transform, }; use futures_core::future::LocalBoxFuture; use crate::{ guard::{self, Guard}, handler::{handler_service, Handler}, middleware::Compat, service::{BoxedHttpServiceFactory, ServiceRequest, ServiceResponse}, Error, FromRequest, HttpResponse, Responder, }; /// A request handler with [guards](guard). /// /// Route uses a builder-like pattern for configuration. If handler is not set, a `404 Not Found` /// handler is used. pub struct Route { service: BoxedHttpServiceFactory, guards: Rc<Vec<Box<dyn Guard>>>, } impl Route { /// Create new route which matches any request. #[allow(clippy::new_without_default)] pub fn new() -> Route { Route { service: boxed::factory(fn_service(|req: ServiceRequest| async { Ok(req.into_response(HttpResponse::NotFound())) })), guards: Rc::new(Vec::new()), } } /// Registers a route middleware. /// /// `mw` is a middleware component (type), that can modify the requests and responses handled by /// this `Route`. /// /// See [`App::wrap`](crate::App::wrap) for more details. #[doc(alias = "middleware")] #[doc(alias = "use")] // nodejs terminology pub fn wrap<M, B>(self, mw: M) -> Route where M: Transform< BoxService<ServiceRequest, ServiceResponse, Error>, ServiceRequest, Response = ServiceResponse<B>, Error = Error, InitError = (), > + 'static, B: MessageBody + 'static, { Route { service: boxed::factory(apply(Compat::new(mw), self.service)), guards: self.guards, } } pub(crate) fn take_guards(&mut self) -> Vec<Box<dyn Guard>> { mem::take(Rc::get_mut(&mut self.guards).unwrap()) } } impl ServiceFactory<ServiceRequest> for Route { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = RouteService; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { let fut = self.service.new_service(()); let guards = Rc::clone(&self.guards); Box::pin(async move { let service = fut.await?; Ok(RouteService { service, guards }) }) } } pub struct RouteService { service: BoxService<ServiceRequest, ServiceResponse, Error>, guards: Rc<Vec<Box<dyn Guard>>>, } impl RouteService { // TODO(breaking): remove pass by ref mut #[allow(clippy::needless_pass_by_ref_mut)] pub fn check(&self, req: &mut ServiceRequest) -> bool { let guard_ctx = req.guard_ctx(); for guard in self.guards.iter() { if !guard.check(&guard_ctx) { return false; } } true } } impl Service<ServiceRequest> for RouteService { type Response = ServiceResponse; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_service::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { self.service.call(req) } } impl Route { /// Add method guard to the route. /// /// # Examples /// ``` /// # use actix_web::*; /// # fn main() { /// App::new().service(web::resource("/path").route( /// web::get() /// .method(http::Method::CONNECT) /// .guard(guard::Header("content-type", "text/plain")) /// .to(|req: HttpRequest| HttpResponse::Ok())) /// ); /// # } /// ``` pub fn method(mut self, method: Method) -> Self { Rc::get_mut(&mut self.guards) .unwrap() .push(Box::new(guard::Method(method))); self } /// Add guard to the route. /// /// # Examples /// ``` /// # use actix_web::*; /// # fn main() { /// App::new().service(web::resource("/path").route( /// web::route() /// .guard(guard::Get()) /// .guard(guard::Header("content-type", "text/plain")) /// .to(|req: HttpRequest| HttpResponse::Ok())) /// ); /// # } /// ``` pub fn guard<F: Guard + 'static>(mut self, f: F) -> Self { Rc::get_mut(&mut self.guards).unwrap().push(Box::new(f)); self } /// Set handler function, use request extractors for parameters. /// /// # Examples /// ``` /// use actix_web::{web, http, App}; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Info { /// username: String, /// } /// /// /// extract path info using serde /// async fn index(info: web::Path<Info>) -> String { /// format!("Welcome {}!", info.username) /// } /// /// let app = App::new().service( /// web::resource("/{username}/index.html") // <- define path parameters /// .route(web::get().to(index)) // <- register handler /// ); /// ``` /// /// It is possible to use multiple extractors for one handler function. /// ``` /// # use std::collections::HashMap; /// # use serde::Deserialize; /// use actix_web::{web, App}; /// /// #[derive(Deserialize)] /// struct Info { /// username: String, /// } /// /// /// extract path info using serde /// async fn index( /// path: web::Path<Info>, /// query: web::Query<HashMap<String, String>>, /// body: web::Json<Info> /// ) -> String { /// format!("Welcome {}!", path.username) /// } /// /// let app = App::new().service( /// web::resource("/{username}/index.html") // <- define path parameters /// .route(web::get().to(index)) /// ); /// ``` pub fn to<F, Args>(mut self, handler: F) -> Self where F: Handler<Args>, Args: FromRequest + 'static, F::Output: Responder + 'static, { self.service = handler_service(handler); self } /// Set raw service to be constructed and called as the request handler. /// /// # Examples /// ``` /// # use std::convert::Infallible; /// # use futures_util::future::LocalBoxFuture; /// # use actix_web::{*, dev::*, http::header}; /// struct HelloWorld; /// /// impl Service<ServiceRequest> for HelloWorld { /// type Response = ServiceResponse; /// type Error = Infallible; /// type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; /// /// dev::always_ready!(); /// /// fn call(&self, req: ServiceRequest) -> Self::Future { /// let (req, _) = req.into_parts(); /// /// let res = HttpResponse::Ok() /// .insert_header(header::ContentType::plaintext()) /// .body("Hello world!"); /// /// Box::pin(async move { Ok(ServiceResponse::new(req, res)) }) /// } /// } /// /// App::new().route( /// "/", /// web::get().service(fn_factory(|| async { Ok(HelloWorld) })), /// ); /// ``` pub fn service<S, E>(mut self, service_factory: S) -> Self where S: ServiceFactory< ServiceRequest, Response = ServiceResponse, Error = E, InitError = (), Config = (), > + 'static, E: Into<Error> + 'static, { self.service = boxed::factory(service_factory.map_err(Into::into)); self } } #[cfg(test)] mod tests { use std::{convert::Infallible, time::Duration}; use actix_rt::time::sleep; use bytes::Bytes; use futures_core::future::LocalBoxFuture; use serde::Serialize; use crate::{ dev::{always_ready, fn_factory, fn_service, Service}, error, http::{header, Method, StatusCode}, middleware::{DefaultHeaders, Logger}, service::{ServiceRequest, ServiceResponse}, test::{call_service, init_service, read_body, TestRequest}, web, App, HttpResponse, }; #[derive(Serialize, PartialEq, Debug)] struct MyObject { name: String, } #[actix_rt::test] async fn test_route() { let srv = init_service( App::new() .service( web::resource("/test") .route(web::get().to(HttpResponse::Ok)) .route(web::put().to(|| async { Err::<HttpResponse, _>(error::ErrorBadRequest("err")) })) .route(web::post().to(|| async { sleep(Duration::from_millis(100)).await; Ok::<_, Infallible>(HttpResponse::Created()) })) .route(web::delete().to(|| async { sleep(Duration::from_millis(100)).await; Err::<HttpResponse, _>(error::ErrorBadRequest("err")) })), ) .service(web::resource("/json").route(web::get().to(|| async { sleep(Duration::from_millis(25)).await; web::Json(MyObject { name: "test".to_string(), }) }))), ) .await; let req = TestRequest::with_uri("/test") .method(Method::GET) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/test") .method(Method::POST) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::CREATED); let req = TestRequest::with_uri("/test") .method(Method::PUT) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/test") .method(Method::DELETE) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/test") .method(Method::HEAD) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); let req = TestRequest::with_uri("/json").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"{\"name\":\"test\"}")); } #[actix_rt::test] async fn route_middleware() { let srv = init_service( App::new() .route("/", web::get().to(HttpResponse::Ok).wrap(Logger::default())) .service( web::resource("/test") .route(web::get().to(HttpResponse::Ok)) .route( web::post() .to(HttpResponse::Created) .wrap(DefaultHeaders::new().add(("x-test", "x-posted"))), ) .route( web::delete() .to(HttpResponse::Accepted) // logger changes body type, proving Compat is not needed .wrap(Logger::default()), ), ), ) .await; let req = TestRequest::get().uri("/test").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); assert!(!res.headers().contains_key("x-test")); let req = TestRequest::post().uri("/test").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::CREATED); assert_eq!(res.headers().get("x-test").unwrap(), "x-posted"); let req = TestRequest::delete().uri("/test").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::ACCEPTED); } #[actix_rt::test] async fn test_service_handler() { struct HelloWorld; impl Service<ServiceRequest> for HelloWorld { type Response = ServiceResponse; type Error = crate::Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; always_ready!(); fn call(&self, req: ServiceRequest) -> Self::Future { let (req, _) = req.into_parts(); let res = HttpResponse::Ok() .insert_header(header::ContentType::plaintext()) .body("Hello world!"); Box::pin(async move { Ok(ServiceResponse::new(req, res)) }) } } let srv = init_service( App::new() .route( "/hello", web::get().service(fn_factory(|| async { Ok(HelloWorld) })), ) .route( "/bye", web::get().service(fn_factory(|| async { Ok::<_, ()>(fn_service(|req: ServiceRequest| async { let (req, _) = req.into_parts(); let res = HttpResponse::Ok() .insert_header(header::ContentType::plaintext()) .body("Goodbye, and thanks for all the fish!"); Ok::<_, Infallible>(ServiceResponse::new(req, res)) })) })), ), ) .await; let req = TestRequest::get().uri("/hello").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"Hello world!")); let req = TestRequest::get().uri("/bye").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let body = read_body(resp).await; assert_eq!( body, Bytes::from_static(b"Goodbye, and thanks for all the fish!") ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/data.rs
actix-web/src/data.rs
use std::{any::type_name, ops::Deref, sync::Arc}; use actix_http::Extensions; use actix_utils::future::{err, ok, Ready}; use futures_core::future::LocalBoxFuture; use serde::{de, Serialize}; use crate::{dev::Payload, error, Error, FromRequest, HttpRequest}; /// Data factory. pub(crate) trait DataFactory { /// Return true if modifications were made to extensions map. fn create(&self, extensions: &mut Extensions) -> bool; } pub(crate) type FnDataFactory = Box<dyn Fn() -> LocalBoxFuture<'static, Result<Box<dyn DataFactory>, ()>>>; /// Application data wrapper and extractor. /// /// # Setting Data /// Data is set using the `app_data` methods on `App`, `Scope`, and `Resource`. If data is wrapped /// in this `Data` type for those calls, it can be used as an extractor. /// /// Note that `Data` should be constructed _outside_ the `HttpServer::new` closure if shared, /// potentially mutable state is desired. `Data` is cheap to clone; internally, it uses an `Arc`. /// /// See also [`App::app_data`](crate::App::app_data), [`Scope::app_data`](crate::Scope::app_data), /// and [`Resource::app_data`](crate::Resource::app_data). /// /// # Extracting `Data` /// Since the Actix Web router layers application data, the returned object will reference the /// "closest" instance of the type. For example, if an `App` stores a `u32`, a nested `Scope` /// also stores a `u32`, and the delegated request handler falls within that `Scope`, then /// extracting a `web::Data<u32>` for that handler will return the `Scope`'s instance. However, /// using the same router set up and a request that does not get captured by the `Scope`, /// `web::<Data<u32>>` would return the `App`'s instance. /// /// If route data is not set for a handler, using `Data<T>` extractor would cause a `500 Internal /// Server Error` response. /// /// See also [`HttpRequest::app_data`] /// and [`ServiceRequest::app_data`](crate::dev::ServiceRequest::app_data). /// /// # Unsized Data /// For types that are unsized, most commonly `dyn T`, `Data` can wrap these types by first /// constructing an `Arc<dyn T>` and using the `From` implementation to convert it. /// /// ``` /// # use std::{fmt::Display, sync::Arc}; /// # use actix_web::web::Data; /// let displayable_arc: Arc<dyn Display> = Arc::new(42usize); /// let displayable_data: Data<dyn Display> = Data::from(displayable_arc); /// ``` /// /// # Examples /// ``` /// use std::sync::Mutex; /// use actix_web::{App, HttpRequest, HttpResponse, Responder, web::{self, Data}}; /// /// struct MyData { /// counter: usize, /// } /// /// /// Use the `Data<T>` extractor to access data in a handler. /// async fn index(data: Data<Mutex<MyData>>) -> impl Responder { /// let mut my_data = data.lock().unwrap(); /// my_data.counter += 1; /// HttpResponse::Ok() /// } /// /// /// Alternatively, use the `HttpRequest::app_data` method to access data in a handler. /// async fn index_alt(req: HttpRequest) -> impl Responder { /// let data = req.app_data::<Data<Mutex<MyData>>>().unwrap(); /// let mut my_data = data.lock().unwrap(); /// my_data.counter += 1; /// HttpResponse::Ok() /// } /// /// let data = Data::new(Mutex::new(MyData { counter: 0 })); /// /// let app = App::new() /// // Store `MyData` in application storage. /// .app_data(Data::clone(&data)) /// .route("/index.html", web::get().to(index)) /// .route("/index-alt.html", web::get().to(index_alt)); /// ``` #[doc(alias = "state")] #[derive(Debug)] pub struct Data<T: ?Sized>(Arc<T>); impl<T> Data<T> { /// Create new `Data` instance. pub fn new(state: T) -> Data<T> { Data(Arc::new(state)) } } impl<T: ?Sized> Data<T> { /// Returns reference to inner `T`. pub fn get_ref(&self) -> &T { self.0.as_ref() } /// Unwraps to the internal `Arc<T>` pub fn into_inner(self) -> Arc<T> { self.0 } } impl<T: ?Sized> Deref for Data<T> { type Target = Arc<T>; fn deref(&self) -> &Arc<T> { &self.0 } } impl<T: ?Sized> Clone for Data<T> { fn clone(&self) -> Data<T> { Data(Arc::clone(&self.0)) } } impl<T: ?Sized> From<Arc<T>> for Data<T> { fn from(arc: Arc<T>) -> Self { Data(arc) } } impl<T: Default> Default for Data<T> { fn default() -> Self { Data::new(T::default()) } } impl<T> Serialize for Data<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } impl<'de, T> de::Deserialize<'de> for Data<T> where T: de::Deserialize<'de>, { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: de::Deserializer<'de>, { Ok(Data::new(T::deserialize(deserializer)?)) } } impl<T: ?Sized + 'static> FromRequest for Data<T> { type Error = Error; type Future = Ready<Result<Self, Error>>; #[inline] fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { if let Some(st) = req.app_data::<Data<T>>() { ok(st.clone()) } else { log::debug!( "Failed to extract `Data<{}>` for `{}` handler. For the Data extractor to work \ correctly, wrap the data with `Data::new()` and pass it to `App::app_data()`. \ Ensure that types align in both the set and retrieve calls.", type_name::<T>(), req.match_name().unwrap_or_else(|| req.path()) ); err(error::ErrorInternalServerError( "Requested application data is not configured correctly. \ View/enable debug logs for more details.", )) } } } impl<T: ?Sized + 'static> DataFactory for Data<T> { fn create(&self, extensions: &mut Extensions) -> bool { extensions.insert(Data(Arc::clone(&self.0))); true } } #[cfg(test)] mod tests { use super::*; use crate::{ dev::Service, http::StatusCode, test::{init_service, TestRequest}, web, App, HttpResponse, }; // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_data_extractor() { let srv = init_service( App::new() .data("TEST".to_string()) .service(web::resource("/").to(|data: web::Data<String>| { assert_eq!(data.to_lowercase(), "test"); HttpResponse::Ok() })), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let srv = init_service( App::new() .data(10u32) .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); let srv = init_service( App::new() .data(10u32) .data(13u32) .app_data(12u64) .app_data(15u64) .default_service(web::to(|n: web::Data<u32>, req: HttpRequest| { // in each case, the latter insertion should be preserved assert_eq!(*req.app_data::<u64>().unwrap(), 15); assert_eq!(*n.into_inner(), 13); HttpResponse::Ok() })), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_app_data_extractor() { let srv = init_service( App::new() .app_data(Data::new(10usize)) .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); let srv = init_service( App::new() .app_data(Data::new(10u32)) .service(web::resource("/").to(|_: web::Data<usize>| HttpResponse::Ok())), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_route_data_extractor() { let srv = init_service( App::new().service( web::resource("/") .data(10usize) .route(web::get().to(|_data: web::Data<usize>| HttpResponse::Ok())), ), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); // different type let srv = init_service( App::new().service( web::resource("/") .data(10u32) .route(web::get().to(|_: web::Data<usize>| HttpResponse::Ok())), ), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_override_data() { let srv = init_service( App::new() .data(1usize) .service(web::resource("/").data(10usize).route(web::get().to( |data: web::Data<usize>| { assert_eq!(**data, 10); HttpResponse::Ok() }, ))), ) .await; let req = TestRequest::default().to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_data_from_arc() { let data_new = Data::new(String::from("test-123")); let data_from_arc = Data::from(Arc::new(String::from("test-123"))); assert_eq!(data_new.0, data_from_arc.0); } #[actix_rt::test] async fn test_data_from_dyn_arc() { trait TestTrait { fn get_num(&self) -> i32; } struct A {} impl TestTrait for A { fn get_num(&self) -> i32 { 42 } } // This works when Sized is required let dyn_arc_box: Arc<Box<dyn TestTrait>> = Arc::new(Box::new(A {})); let data_arc_box = Data::from(dyn_arc_box); // This works when Data Sized Bound is removed let dyn_arc: Arc<dyn TestTrait> = Arc::new(A {}); let data_arc = Data::from(dyn_arc); assert_eq!(data_arc_box.get_num(), data_arc.get_num()) } #[actix_rt::test] async fn test_dyn_data_into_arc() { trait TestTrait { fn get_num(&self) -> i32; } struct A {} impl TestTrait for A { fn get_num(&self) -> i32 { 42 } } let dyn_arc: Arc<dyn TestTrait> = Arc::new(A {}); let data_arc = Data::from(dyn_arc); let arc_from_data = data_arc.clone().into_inner(); assert_eq!(data_arc.get_num(), arc_from_data.get_num()) } #[actix_rt::test] async fn test_get_ref_from_dyn_data() { trait TestTrait { fn get_num(&self) -> i32; } struct A {} impl TestTrait for A { fn get_num(&self) -> i32 { 42 } } let dyn_arc: Arc<dyn TestTrait> = Arc::new(A {}); let data_arc = Data::from(dyn_arc); let ref_data = data_arc.get_ref(); assert_eq!(data_arc.get_num(), ref_data.get_num()) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/handler.rs
actix-web/src/handler.rs
use std::future::Future; use actix_service::{boxed, fn_service}; use crate::{ service::{BoxedHttpServiceFactory, ServiceRequest, ServiceResponse}, FromRequest, HttpResponse, Responder, }; /// The interface for request handlers. /// /// # What Is A Request Handler /// /// In short, a handler is just an async function that receives request-based arguments, in any /// order, and returns something that can be converted to a response. /// /// In particular, a request handler has three requirements: /// /// 1. It is an async function (or a function/closure that returns an appropriate future); /// 1. The function parameters (up to 12) implement [`FromRequest`]; /// 1. The async function (or future) resolves to a type that can be converted into an /// [`HttpResponse`] (i.e., it implements the [`Responder`] trait). /// /// /// # Compiler Errors /// /// If you get the error `the trait Handler<_> is not implemented`, then your handler does not /// fulfill the _first_ of the above requirements. (It could also mean that you're attempting to use /// a macro-routed handler in a manual routing context like `web::get().to(handler)`, which is not /// supported). Breaking the other requirements manifests as errors on implementing [`FromRequest`] /// and [`Responder`], respectively. /// /// # How Do Handlers Receive Variable Numbers Of Arguments /// /// Rest assured there is no macro magic here; it's just traits. /// /// The first thing to note is that [`FromRequest`] is implemented for tuples (up to 12 in length). /// /// Secondly, the `Handler` trait is implemented for functions (up to an [arity] of 12) in a way /// that aligns their parameter positions with a corresponding tuple of types (becoming the `Args` /// type parameter for this trait). /// /// Thanks to Rust's type system, Actix Web can infer the function parameter types. During the /// extraction step, the parameter types are described as a tuple type, [`from_request`] is run on /// that tuple, and the `Handler::call` implementation for that particular function arity /// destructures the tuple into its component types and calls your handler function with them. /// /// In pseudo-code the process looks something like this: /// /// ```ignore /// async fn my_handler(body: String, state: web::Data<MyState>) -> impl Responder { /// ... /// } /// /// // the function params above described as a tuple, names do not matter, only position /// type InferredMyHandlerArgs = (String, web::Data<MyState>); /// /// // create tuple of arguments to be passed to handler /// let args = InferredMyHandlerArgs::from_request(&request, &payload).await; /// /// // call handler with argument tuple /// let response = Handler::call(&my_handler, args).await; /// /// // which is effectively... /// /// let (body, state) = args; /// let response = my_handler(body, state).await; /// ``` /// /// This is the source code for the 2-parameter implementation of `Handler` to help illustrate the /// bounds of the handler call after argument extraction: /// ```ignore /// impl<Func, Fut, Arg1, Arg2> Handler<(Arg1, Arg2)> for Func /// where /// Func: Fn(Arg1, Arg2) -> Fut + Clone + 'static, /// Fut: Future, /// { /// type Output = Fut::Output; /// type Future = Fut; /// /// fn call(&self, (arg1, arg2): (Arg1, Arg2)) -> Self::Future { /// (self)(arg1, arg2) /// } /// } /// ``` /// /// [arity]: https://en.wikipedia.org/wiki/Arity /// [`from_request`]: FromRequest::from_request pub trait Handler<Args>: Clone + 'static { type Output; type Future: Future<Output = Self::Output>; fn call(&self, args: Args) -> Self::Future; } pub(crate) fn handler_service<F, Args>(handler: F) -> BoxedHttpServiceFactory where F: Handler<Args>, Args: FromRequest, F::Output: Responder, { boxed::factory(fn_service(move |req: ServiceRequest| { let handler = handler.clone(); async move { let (req, mut payload) = req.into_parts(); let res = match Args::from_request(&req, &mut payload).await { Err(err) => HttpResponse::from_error(err), Ok(data) => handler .call(data) .await .respond_to(&req) .map_into_boxed_body(), }; Ok(ServiceResponse::new(req, res)) } })) } /// Generates a [`Handler`] trait impl for N-ary functions where N is specified with a sequence of /// space separated type parameters. /// /// # Examples /// ```ignore /// factory_tuple! {} // implements Handler for types: fn() -> R /// factory_tuple! { A B C } // implements Handler for types: fn(A, B, C) -> R /// ``` macro_rules! factory_tuple ({ $($param:ident)* } => { impl<Func, Fut, $($param,)*> Handler<($($param,)*)> for Func where Func: Fn($($param),*) -> Fut + Clone + 'static, Fut: Future, { type Output = Fut::Output; type Future = Fut; #[inline] #[allow(non_snake_case)] fn call(&self, ($($param,)*): ($($param,)*)) -> Self::Future { (self)($($param,)*) } } }); factory_tuple! {} factory_tuple! { A } factory_tuple! { A B } factory_tuple! { A B C } factory_tuple! { A B C D } factory_tuple! { A B C D E } factory_tuple! { A B C D E F } factory_tuple! { A B C D E F G } factory_tuple! { A B C D E F G H } factory_tuple! { A B C D E F G H I } factory_tuple! { A B C D E F G H I J } factory_tuple! { A B C D E F G H I J K } factory_tuple! { A B C D E F G H I J K L } factory_tuple! { A B C D E F G H I J K L M } factory_tuple! { A B C D E F G H I J K L M N } factory_tuple! { A B C D E F G H I J K L M N O } factory_tuple! { A B C D E F G H I J K L M N O P } #[cfg(test)] mod tests { use super::*; fn assert_impl_handler<T: FromRequest>(_: impl Handler<T>) {} #[test] fn arg_number() { async fn handler_min() {} #[rustfmt::skip] #[allow(clippy::too_many_arguments, clippy::just_underscores_and_digits, clippy::let_unit_value)] async fn handler_max( _01: (), _02: (), _03: (), _04: (), _05: (), _06: (), _07: (), _08: (), _09: (), _10: (), _11: (), _12: (), _13: (), _14: (), _15: (), _16: (), ) {} assert_impl_handler(handler_min); assert_impl_handler(handler_max); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/error/internal.rs
actix-web/src/error/internal.rs
use std::{cell::RefCell, fmt, io::Write as _}; use actix_http::{ body::BoxBody, header::{self, TryIntoHeaderValue as _}, StatusCode, }; use bytes::{BufMut as _, BytesMut}; use crate::{Error, HttpRequest, HttpResponse, Responder, ResponseError}; /// Wraps errors to alter the generated response status code. /// /// In following example, the `io::Error` is wrapped into `ErrorBadRequest` which will generate a /// response with the 400 Bad Request status code instead of the usual status code generated by /// an `io::Error`. /// /// # Examples /// ``` /// # use std::io; /// # use actix_web::{error, HttpRequest}; /// async fn handler_error() -> Result<String, actix_web::Error> { /// let err = io::Error::new(io::ErrorKind::Other, "error"); /// Err(error::ErrorBadRequest(err)) /// } /// ``` pub struct InternalError<T> { cause: T, status: InternalErrorType, } enum InternalErrorType { Status(StatusCode), Response(RefCell<Option<HttpResponse>>), } impl<T> InternalError<T> { /// Constructs an `InternalError` with given status code. pub fn new(cause: T, status: StatusCode) -> Self { InternalError { cause, status: InternalErrorType::Status(status), } } /// Constructs an `InternalError` with pre-defined response. pub fn from_response(cause: T, response: HttpResponse) -> Self { InternalError { cause, status: InternalErrorType::Response(RefCell::new(Some(response))), } } } impl<T: fmt::Debug> fmt::Debug for InternalError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.cause.fmt(f) } } impl<T: fmt::Display> fmt::Display for InternalError<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.cause.fmt(f) } } impl<T> ResponseError for InternalError<T> where T: fmt::Debug + fmt::Display, { fn status_code(&self) -> StatusCode { match self.status { InternalErrorType::Status(st) => st, InternalErrorType::Response(ref resp) => { if let Some(resp) = resp.borrow().as_ref() { resp.head().status } else { StatusCode::INTERNAL_SERVER_ERROR } } } } fn error_response(&self) -> HttpResponse { match self.status { InternalErrorType::Status(status) => { let mut res = HttpResponse::new(status); let mut buf = BytesMut::new().writer(); let _ = write!(buf, "{}", self); let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res.set_body(BoxBody::new(buf.into_inner())) } InternalErrorType::Response(ref resp) => { if let Some(resp) = resp.borrow_mut().take() { resp } else { HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR) } } } } } impl<T> Responder for InternalError<T> where T: fmt::Debug + fmt::Display + 'static, { type Body = BoxBody; fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> { HttpResponse::from_error(self) } } macro_rules! error_helper { ($name:ident, $status:ident) => { #[doc = concat!("Helper function that wraps any error and generates a `", stringify!($status), "` response.")] #[allow(non_snake_case)] pub fn $name<T>(err: T) -> Error where T: fmt::Debug + fmt::Display + 'static, { InternalError::new(err, StatusCode::$status).into() } }; } error_helper!(ErrorBadRequest, BAD_REQUEST); error_helper!(ErrorUnauthorized, UNAUTHORIZED); error_helper!(ErrorPaymentRequired, PAYMENT_REQUIRED); error_helper!(ErrorForbidden, FORBIDDEN); error_helper!(ErrorNotFound, NOT_FOUND); error_helper!(ErrorMethodNotAllowed, METHOD_NOT_ALLOWED); error_helper!(ErrorNotAcceptable, NOT_ACCEPTABLE); error_helper!( ErrorProxyAuthenticationRequired, PROXY_AUTHENTICATION_REQUIRED ); error_helper!(ErrorRequestTimeout, REQUEST_TIMEOUT); error_helper!(ErrorConflict, CONFLICT); error_helper!(ErrorGone, GONE); error_helper!(ErrorLengthRequired, LENGTH_REQUIRED); error_helper!(ErrorPayloadTooLarge, PAYLOAD_TOO_LARGE); error_helper!(ErrorUriTooLong, URI_TOO_LONG); error_helper!(ErrorUnsupportedMediaType, UNSUPPORTED_MEDIA_TYPE); error_helper!(ErrorRangeNotSatisfiable, RANGE_NOT_SATISFIABLE); error_helper!(ErrorImATeapot, IM_A_TEAPOT); error_helper!(ErrorMisdirectedRequest, MISDIRECTED_REQUEST); error_helper!(ErrorUnprocessableEntity, UNPROCESSABLE_ENTITY); error_helper!(ErrorLocked, LOCKED); error_helper!(ErrorFailedDependency, FAILED_DEPENDENCY); error_helper!(ErrorUpgradeRequired, UPGRADE_REQUIRED); error_helper!(ErrorPreconditionFailed, PRECONDITION_FAILED); error_helper!(ErrorPreconditionRequired, PRECONDITION_REQUIRED); error_helper!(ErrorTooManyRequests, TOO_MANY_REQUESTS); error_helper!( ErrorRequestHeaderFieldsTooLarge, REQUEST_HEADER_FIELDS_TOO_LARGE ); error_helper!( ErrorUnavailableForLegalReasons, UNAVAILABLE_FOR_LEGAL_REASONS ); error_helper!(ErrorExpectationFailed, EXPECTATION_FAILED); error_helper!(ErrorInternalServerError, INTERNAL_SERVER_ERROR); error_helper!(ErrorNotImplemented, NOT_IMPLEMENTED); error_helper!(ErrorBadGateway, BAD_GATEWAY); error_helper!(ErrorServiceUnavailable, SERVICE_UNAVAILABLE); error_helper!(ErrorGatewayTimeout, GATEWAY_TIMEOUT); error_helper!(ErrorHttpVersionNotSupported, HTTP_VERSION_NOT_SUPPORTED); error_helper!(ErrorVariantAlsoNegotiates, VARIANT_ALSO_NEGOTIATES); error_helper!(ErrorInsufficientStorage, INSUFFICIENT_STORAGE); error_helper!(ErrorLoopDetected, LOOP_DETECTED); error_helper!(ErrorNotExtended, NOT_EXTENDED); error_helper!( ErrorNetworkAuthenticationRequired, NETWORK_AUTHENTICATION_REQUIRED ); #[cfg(test)] mod tests { use actix_http::error::ParseError; use super::*; #[test] fn test_internal_error() { let err = InternalError::from_response(ParseError::Method, HttpResponse::Ok().finish()); let resp: HttpResponse = err.error_response(); assert_eq!(resp.status(), StatusCode::OK); } #[test] fn test_error_helpers() { let res: HttpResponse = ErrorBadRequest("err").into(); assert_eq!(res.status(), StatusCode::BAD_REQUEST); let res: HttpResponse = ErrorUnauthorized("err").into(); assert_eq!(res.status(), StatusCode::UNAUTHORIZED); let res: HttpResponse = ErrorPaymentRequired("err").into(); assert_eq!(res.status(), StatusCode::PAYMENT_REQUIRED); let res: HttpResponse = ErrorForbidden("err").into(); assert_eq!(res.status(), StatusCode::FORBIDDEN); let res: HttpResponse = ErrorNotFound("err").into(); assert_eq!(res.status(), StatusCode::NOT_FOUND); let res: HttpResponse = ErrorMethodNotAllowed("err").into(); assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED); let res: HttpResponse = ErrorNotAcceptable("err").into(); assert_eq!(res.status(), StatusCode::NOT_ACCEPTABLE); let res: HttpResponse = ErrorProxyAuthenticationRequired("err").into(); assert_eq!(res.status(), StatusCode::PROXY_AUTHENTICATION_REQUIRED); let res: HttpResponse = ErrorRequestTimeout("err").into(); assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT); let res: HttpResponse = ErrorConflict("err").into(); assert_eq!(res.status(), StatusCode::CONFLICT); let res: HttpResponse = ErrorGone("err").into(); assert_eq!(res.status(), StatusCode::GONE); let res: HttpResponse = ErrorLengthRequired("err").into(); assert_eq!(res.status(), StatusCode::LENGTH_REQUIRED); let res: HttpResponse = ErrorPreconditionFailed("err").into(); assert_eq!(res.status(), StatusCode::PRECONDITION_FAILED); let res: HttpResponse = ErrorPayloadTooLarge("err").into(); assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE); let res: HttpResponse = ErrorUriTooLong("err").into(); assert_eq!(res.status(), StatusCode::URI_TOO_LONG); let res: HttpResponse = ErrorUnsupportedMediaType("err").into(); assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); let res: HttpResponse = ErrorRangeNotSatisfiable("err").into(); assert_eq!(res.status(), StatusCode::RANGE_NOT_SATISFIABLE); let res: HttpResponse = ErrorExpectationFailed("err").into(); assert_eq!(res.status(), StatusCode::EXPECTATION_FAILED); let res: HttpResponse = ErrorImATeapot("err").into(); assert_eq!(res.status(), StatusCode::IM_A_TEAPOT); let res: HttpResponse = ErrorMisdirectedRequest("err").into(); assert_eq!(res.status(), StatusCode::MISDIRECTED_REQUEST); let res: HttpResponse = ErrorUnprocessableEntity("err").into(); assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); let res: HttpResponse = ErrorLocked("err").into(); assert_eq!(res.status(), StatusCode::LOCKED); let res: HttpResponse = ErrorFailedDependency("err").into(); assert_eq!(res.status(), StatusCode::FAILED_DEPENDENCY); let res: HttpResponse = ErrorUpgradeRequired("err").into(); assert_eq!(res.status(), StatusCode::UPGRADE_REQUIRED); let res: HttpResponse = ErrorPreconditionRequired("err").into(); assert_eq!(res.status(), StatusCode::PRECONDITION_REQUIRED); let res: HttpResponse = ErrorTooManyRequests("err").into(); assert_eq!(res.status(), StatusCode::TOO_MANY_REQUESTS); let res: HttpResponse = ErrorRequestHeaderFieldsTooLarge("err").into(); assert_eq!(res.status(), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE); let res: HttpResponse = ErrorUnavailableForLegalReasons("err").into(); assert_eq!(res.status(), StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS); let res: HttpResponse = ErrorInternalServerError("err").into(); assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); let res: HttpResponse = ErrorNotImplemented("err").into(); assert_eq!(res.status(), StatusCode::NOT_IMPLEMENTED); let res: HttpResponse = ErrorBadGateway("err").into(); assert_eq!(res.status(), StatusCode::BAD_GATEWAY); let res: HttpResponse = ErrorServiceUnavailable("err").into(); assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE); let res: HttpResponse = ErrorGatewayTimeout("err").into(); assert_eq!(res.status(), StatusCode::GATEWAY_TIMEOUT); let res: HttpResponse = ErrorHttpVersionNotSupported("err").into(); assert_eq!(res.status(), StatusCode::HTTP_VERSION_NOT_SUPPORTED); let res: HttpResponse = ErrorVariantAlsoNegotiates("err").into(); assert_eq!(res.status(), StatusCode::VARIANT_ALSO_NEGOTIATES); let res: HttpResponse = ErrorInsufficientStorage("err").into(); assert_eq!(res.status(), StatusCode::INSUFFICIENT_STORAGE); let res: HttpResponse = ErrorLoopDetected("err").into(); assert_eq!(res.status(), StatusCode::LOOP_DETECTED); let res: HttpResponse = ErrorNotExtended("err").into(); assert_eq!(res.status(), StatusCode::NOT_EXTENDED); let res: HttpResponse = ErrorNetworkAuthenticationRequired("err").into(); assert_eq!(res.status(), StatusCode::NETWORK_AUTHENTICATION_REQUIRED); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/error/response_error.rs
actix-web/src/error/response_error.rs
//! `ResponseError` trait and foreign impls. use std::{ convert::Infallible, error::Error as StdError, fmt, io::{self, Write as _}, }; use bytes::BytesMut; use crate::{ body::BoxBody, error::{downcast_dyn, downcast_get_type_id}, helpers, http::{ header::{self, TryIntoHeaderValue}, StatusCode, }, HttpResponse, }; /// Errors that can generate responses. // TODO: flesh out documentation pub trait ResponseError: fmt::Debug + fmt::Display { /// Returns appropriate status code for error. /// /// A 500 Internal Server Error is used by default. If [error_response](Self::error_response) is /// also implemented and does not call `self.status_code()`, then this will not be used. fn status_code(&self) -> StatusCode { StatusCode::INTERNAL_SERVER_ERROR } /// Creates full response for error. /// /// By default, the generated response uses a 500 Internal Server Error status code, a /// `Content-Type` of `text/plain`, and the body is set to `Self`'s `Display` impl. fn error_response(&self) -> HttpResponse<BoxBody> { let mut res = HttpResponse::new(self.status_code()); let mut buf = BytesMut::new(); let _ = write!(helpers::MutWriter(&mut buf), "{}", self); let mime = mime::TEXT_PLAIN_UTF_8.try_into_value().unwrap(); res.headers_mut().insert(header::CONTENT_TYPE, mime); res.set_body(BoxBody::new(buf)) } downcast_get_type_id!(); } downcast_dyn!(ResponseError); impl ResponseError for Box<dyn StdError + 'static> {} impl ResponseError for Infallible { fn status_code(&self) -> StatusCode { match *self {} } fn error_response(&self) -> HttpResponse<BoxBody> { match *self {} } } #[cfg(feature = "openssl")] impl ResponseError for actix_tls::accept::openssl::reexports::Error {} impl ResponseError for serde::de::value::Error { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } impl ResponseError for serde_json::Error {} impl ResponseError for serde_urlencoded::ser::Error {} impl ResponseError for std::str::Utf8Error { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } impl ResponseError for std::io::Error { fn status_code(&self) -> StatusCode { match self.kind() { io::ErrorKind::NotFound => StatusCode::NOT_FOUND, io::ErrorKind::PermissionDenied => StatusCode::FORBIDDEN, _ => StatusCode::INTERNAL_SERVER_ERROR, } } } impl ResponseError for actix_http::error::HttpError {} impl ResponseError for actix_http::Error { fn status_code(&self) -> StatusCode { StatusCode::INTERNAL_SERVER_ERROR } fn error_response(&self) -> HttpResponse<BoxBody> { HttpResponse::with_body(self.status_code(), self.to_string()).map_into_boxed_body() } } impl ResponseError for actix_http::header::InvalidHeaderValue { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } impl ResponseError for actix_http::error::ParseError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } impl ResponseError for actix_http::error::PayloadError { fn status_code(&self) -> StatusCode { match *self { actix_http::error::PayloadError::Overflow => StatusCode::PAYLOAD_TOO_LARGE, _ => StatusCode::BAD_REQUEST, } } } impl ResponseError for actix_http::error::ContentTypeError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } #[cfg(feature = "ws")] impl ResponseError for actix_http::ws::HandshakeError { fn error_response(&self) -> HttpResponse<BoxBody> { actix_http::Response::from(self) .map_into_boxed_body() .into() } } #[cfg(feature = "ws")] impl ResponseError for actix_http::ws::ProtocolError {} #[cfg(test)] mod tests { use super::*; #[test] fn test_error_casting() { use actix_http::error::{ContentTypeError, PayloadError}; let err = PayloadError::Overflow; let resp_err: &dyn ResponseError = &err; let err = resp_err.downcast_ref::<PayloadError>().unwrap(); assert_eq!(err.to_string(), "payload reached size limit"); let not_err = resp_err.downcast_ref::<ContentTypeError>(); assert!(not_err.is_none()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/error/error.rs
actix-web/src/error/error.rs
use std::{error::Error as StdError, fmt}; use actix_http::{body::BoxBody, Response}; use crate::{HttpResponse, ResponseError}; /// General purpose Actix Web error. /// /// An Actix Web error is used to carry errors from `std::error` through actix in a convenient way. /// It can be created through converting errors with `into()`. /// /// Whenever it is created from an external object a response error is created for it that can be /// used to create an HTTP response from it this means that if you have access to an actix `Error` /// you can always get a `ResponseError` reference from it. pub struct Error { cause: Box<dyn ResponseError>, } impl Error { /// Returns the reference to the underlying `ResponseError`. pub fn as_response_error(&self) -> &dyn ResponseError { self.cause.as_ref() } /// Similar to `as_response_error` but downcasts. pub fn as_error<T: ResponseError + 'static>(&self) -> Option<&T> { <dyn ResponseError>::downcast_ref(self.cause.as_ref()) } /// Shortcut for creating an `HttpResponse`. pub fn error_response(&self) -> HttpResponse { self.cause.error_response() } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.cause, f) } } impl fmt::Debug for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", &self.cause) } } impl StdError for Error { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } /// `Error` for any error that implements `ResponseError` impl<T: ResponseError + 'static> From<T> for Error { fn from(err: T) -> Error { Error { cause: Box::new(err), } } } impl From<Box<dyn ResponseError>> for Error { fn from(value: Box<dyn ResponseError>) -> Self { Error { cause: value } } } impl From<Error> for Response<BoxBody> { fn from(err: Error) -> Response<BoxBody> { err.error_response().into() } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/error/macros.rs
actix-web/src/error/macros.rs
macro_rules! downcast_get_type_id { () => { /// A helper method to get the type ID of the type /// this trait is implemented on. /// This method is unsafe to *implement*, since `downcast_ref` relies /// on the returned `TypeId` to perform a cast. /// /// Unfortunately, Rust has no notion of a trait method that is /// unsafe to implement (marking it as `unsafe` makes it unsafe /// to *call*). As a workaround, we require this method /// to return a private type along with the `TypeId`. This /// private type (`PrivateHelper`) has a private constructor, /// making it impossible for safe code to construct outside of /// this module. This ensures that safe code cannot violate /// type-safety by implementing this method. /// /// We also take `PrivateHelper` as a parameter, to ensure that /// safe code cannot obtain a `PrivateHelper` instance by /// delegating to an existing implementation of `__private_get_type_id__` #[doc(hidden)] #[allow(dead_code)] fn __private_get_type_id__(&self, _: PrivateHelper) -> (std::any::TypeId, PrivateHelper) where Self: 'static, { (std::any::TypeId::of::<Self>(), PrivateHelper(())) } }; } // Generate implementation for dyn $name macro_rules! downcast_dyn { ($name:ident) => { /// A struct with a private constructor, for use with /// `__private_get_type_id__`. Its single field is private, /// ensuring that it can only be constructed from this module #[doc(hidden)] #[allow(dead_code)] pub struct PrivateHelper(()); impl dyn $name + 'static { /// Downcasts generic body to a specific type. #[allow(dead_code)] pub fn downcast_ref<T: $name + 'static>(&self) -> Option<&T> { if self.__private_get_type_id__(PrivateHelper(())).0 == std::any::TypeId::of::<T>() { // SAFETY: external crates cannot override the default // implementation of `__private_get_type_id__`, since // it requires returning a private type. We can therefore // rely on the returned `TypeId`, which ensures that this // case is correct. unsafe { Some(&*(self as *const dyn $name as *const T)) } } else { None } } /// Downcasts a generic body to a mutable specific type. #[allow(dead_code)] pub fn downcast_mut<T: $name + 'static>(&mut self) -> Option<&mut T> { if self.__private_get_type_id__(PrivateHelper(())).0 == std::any::TypeId::of::<T>() { // SAFETY: external crates cannot override the default // implementation of `__private_get_type_id__`, since // it requires returning a private type. We can therefore // rely on the returned `TypeId`, which ensures that this // case is correct. unsafe { Some(&mut *(self as *const dyn $name as *const T as *mut T)) } } else { None } } } }; } pub(crate) use downcast_dyn; pub(crate) use downcast_get_type_id; #[cfg(test)] mod tests { #![allow(clippy::upper_case_acronyms)] trait MB { downcast_get_type_id!(); } downcast_dyn!(MB); impl MB for String {} impl MB for () {} #[actix_rt::test] async fn test_any_casting() { let mut body = String::from("hello cast"); let resp_body: &mut dyn MB = &mut body; let body = resp_body.downcast_ref::<String>().unwrap(); assert_eq!(body, "hello cast"); let body = resp_body.downcast_mut::<String>().unwrap(); body.push('!'); let body = resp_body.downcast_ref::<String>().unwrap(); assert_eq!(body, "hello cast!"); let not_body = resp_body.downcast_ref::<()>(); assert!(not_body.is_none()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/error/mod.rs
actix-web/src/error/mod.rs
//! Error and Result module // This is meant to be a glob import of the whole error module except for `Error`. Rustdoc can't yet // correctly resolve the conflicting `Error` type defined in this module, so these re-exports are // expanded manually. // // See <https://github.com/rust-lang/rust/issues/83375> pub use actix_http::error::{ContentTypeError, DispatchError, HttpError, ParseError, PayloadError}; use derive_more::{Display, Error, From}; use serde_json::error::Error as JsonError; use serde_urlencoded::{de::Error as FormDeError, ser::Error as FormError}; use url::ParseError as UrlParseError; use crate::http::StatusCode; #[allow(clippy::module_inception)] mod error; mod internal; mod macros; mod response_error; pub(crate) use self::macros::{downcast_dyn, downcast_get_type_id}; pub use self::{error::Error, internal::*, response_error::ResponseError}; pub use crate::types::EitherExtractError; /// A convenience [`Result`](std::result::Result) for Actix Web operations. /// /// This type alias is generally used to avoid writing out `actix_http::Error` directly. pub type Result<T, E = Error> = std::result::Result<T, E>; /// An error representing a problem running a blocking task on a thread pool. #[derive(Debug, Display, Error)] #[display("Blocking thread pool is shut down unexpectedly")] #[non_exhaustive] pub struct BlockingError; impl ResponseError for crate::error::BlockingError {} /// Errors which can occur when attempting to generate resource uri. #[derive(Debug, PartialEq, Eq, Display, Error, From)] #[non_exhaustive] pub enum UrlGenerationError { /// Resource not found. #[display("Resource not found")] ResourceNotFound, /// Not all URL parameters covered. #[display("Not all URL parameters covered")] NotEnoughElements, /// URL parse error. #[display("{}", _0)] ParseError(UrlParseError), } impl ResponseError for UrlGenerationError {} /// A set of errors that can occur during parsing urlencoded payloads #[derive(Debug, Display, Error, From)] #[non_exhaustive] pub enum UrlencodedError { /// Can not decode chunked transfer encoding. #[display("Can not decode chunked transfer encoding.")] Chunked, /// Payload size is larger than allowed. (default limit: 256kB). #[display( "URL encoded payload is larger ({} bytes) than allowed (limit: {} bytes).", size, limit )] Overflow { size: usize, limit: usize }, /// Payload size is now known. #[display("Payload size is now known.")] UnknownLength, /// Content type error. #[display("Content type error.")] ContentType, /// Parse error. #[display("Parse error: {}.", _0)] Parse(FormDeError), /// Encoding error. #[display("Encoding error.")] Encoding, /// Serialize error. #[display("Serialize error: {}.", _0)] Serialize(FormError), /// Payload error. #[display("Error that occur during reading payload: {}.", _0)] Payload(PayloadError), } impl ResponseError for UrlencodedError { fn status_code(&self) -> StatusCode { match self { Self::Overflow { .. } => StatusCode::PAYLOAD_TOO_LARGE, Self::UnknownLength => StatusCode::LENGTH_REQUIRED, Self::ContentType => StatusCode::UNSUPPORTED_MEDIA_TYPE, Self::Payload(err) => err.status_code(), _ => StatusCode::BAD_REQUEST, } } } /// A set of errors that can occur during parsing json payloads #[derive(Debug, Display, Error)] #[non_exhaustive] pub enum JsonPayloadError { /// Payload size is bigger than allowed & content length header set. (default: 2MB) #[display( "JSON payload ({} bytes) is larger than allowed (limit: {} bytes).", length, limit )] OverflowKnownLength { length: usize, limit: usize }, /// Payload size is bigger than allowed but no content length header set. (default: 2MB) #[display("JSON payload has exceeded limit ({} bytes).", limit)] Overflow { limit: usize }, /// Content type error #[display("Content type error")] ContentType, /// Deserialize error #[display("Json deserialize error: {}", _0)] Deserialize(JsonError), /// Serialize error #[display("Json serialize error: {}", _0)] Serialize(JsonError), /// Payload error #[display("Error that occur during reading payload: {}", _0)] Payload(PayloadError), } impl From<PayloadError> for JsonPayloadError { fn from(err: PayloadError) -> Self { Self::Payload(err) } } impl ResponseError for JsonPayloadError { fn status_code(&self) -> StatusCode { match self { Self::OverflowKnownLength { length: _, limit: _, } => StatusCode::PAYLOAD_TOO_LARGE, Self::Overflow { limit: _ } => StatusCode::PAYLOAD_TOO_LARGE, Self::Serialize(_) => StatusCode::INTERNAL_SERVER_ERROR, Self::Payload(err) => err.status_code(), _ => StatusCode::BAD_REQUEST, } } } /// A set of errors that can occur during parsing request paths #[derive(Debug, Display, Error)] #[non_exhaustive] pub enum PathError { /// Deserialize error #[display("Path deserialize error: {}", _0)] Deserialize(serde::de::value::Error), } /// Return `BadRequest` for `PathError` impl ResponseError for PathError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } /// A set of errors that can occur during parsing query strings. #[derive(Debug, Display, Error, From)] #[non_exhaustive] pub enum QueryPayloadError { /// Query deserialize error. #[display("Query deserialize error: {}", _0)] Deserialize(serde::de::value::Error), } impl ResponseError for QueryPayloadError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } /// Error type returned when reading body as lines. #[derive(Debug, Display, Error, From)] #[non_exhaustive] pub enum ReadlinesError { #[display("Encoding error")] /// Payload size is bigger than allowed. (default: 256kB) EncodingError, /// Payload error. #[display("Error that occur during reading payload: {}", _0)] Payload(PayloadError), /// Line limit exceeded. #[display("Line limit exceeded")] LimitOverflow, /// ContentType error. #[display("Content-type error")] ContentTypeError(ContentTypeError), } impl ResponseError for ReadlinesError { fn status_code(&self) -> StatusCode { match *self { ReadlinesError::LimitOverflow => StatusCode::PAYLOAD_TOO_LARGE, _ => StatusCode::BAD_REQUEST, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_urlencoded_error() { let resp = UrlencodedError::Overflow { size: 0, limit: 0 }.error_response(); assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE); let resp = UrlencodedError::UnknownLength.error_response(); assert_eq!(resp.status(), StatusCode::LENGTH_REQUIRED); let resp = UrlencodedError::ContentType.error_response(); assert_eq!(resp.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); } #[test] fn test_json_payload_error() { let resp = JsonPayloadError::OverflowKnownLength { length: 0, limit: 0, } .error_response(); assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE); let resp = JsonPayloadError::Overflow { limit: 0 }.error_response(); assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE); let resp = JsonPayloadError::ContentType.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } #[test] fn test_query_payload_error() { let resp = QueryPayloadError::Deserialize( serde_urlencoded::from_str::<i32>("bad query").unwrap_err(), ) .error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } #[test] fn test_readlines_error() { let resp = ReadlinesError::LimitOverflow.error_response(); assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE); let resp = ReadlinesError::EncodingError.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/err_handlers.rs
actix-web/src/middleware/err_handlers.rs
//! For middleware documentation, see [`ErrorHandlers`]. use std::{ future::Future, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_service::{Service, Transform}; use foldhash::HashMap as FoldHashMap; use futures_core::{future::LocalBoxFuture, ready}; use pin_project_lite::pin_project; use crate::{ body::EitherBody, dev::{ServiceRequest, ServiceResponse}, http::StatusCode, Error, Result, }; /// Return type for [`ErrorHandlers`] custom handlers. pub enum ErrorHandlerResponse<B> { /// Immediate HTTP response. Response(ServiceResponse<EitherBody<B>>), /// A future that resolves to an HTTP response. Future(LocalBoxFuture<'static, Result<ServiceResponse<EitherBody<B>>, Error>>), } type ErrorHandler<B> = dyn Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>; type DefaultHandler<B> = Option<Rc<ErrorHandler<B>>>; /// Middleware for registering custom status code based error handlers. /// /// Register handlers with the [`ErrorHandlers::handler()`] method to register a custom error handler /// for a given status code. Handlers can modify existing responses or create completely new ones. /// /// To register a default handler, use the [`ErrorHandlers::default_handler()`] method. This /// handler will be used only if a response has an error status code (400-599) that isn't covered by /// a more specific handler (set with the [`handler()`][ErrorHandlers::handler] method). See examples /// below. /// /// To register a default for only client errors (400-499) or only server errors (500-599), use the /// [`ErrorHandlers::default_handler_client()`] and [`ErrorHandlers::default_handler_server()`] /// methods, respectively. /// /// Any response with a status code that isn't covered by a specific handler or a default handler /// will pass by unchanged by this middleware. /// /// # Examples /// /// Adding a header: /// /// ``` /// use actix_web::{ /// dev::ServiceResponse, /// http::{header, StatusCode}, /// middleware::{ErrorHandlerResponse, ErrorHandlers}, /// web, App, HttpResponse, Result, /// }; /// /// fn add_error_header<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { /// res.response_mut().headers_mut().insert( /// header::CONTENT_TYPE, /// header::HeaderValue::from_static("Error"), /// ); /// /// // body is unchanged, map to "left" slot /// Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) /// } /// /// let app = App::new() /// .wrap(ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, add_error_header)) /// .service(web::resource("/").route(web::get().to(HttpResponse::InternalServerError))); /// ``` /// /// Modifying response body: /// /// ``` /// use actix_web::{ /// dev::ServiceResponse, /// http::{header, StatusCode}, /// middleware::{ErrorHandlerResponse, ErrorHandlers}, /// web, App, HttpResponse, Result, /// }; /// /// fn add_error_body<B>(res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { /// // split service response into request and response components /// let (req, res) = res.into_parts(); /// /// // set body of response to modified body /// let res = res.set_body("An error occurred."); /// /// // modified bodies need to be boxed and placed in the "right" slot /// let res = ServiceResponse::new(req, res) /// .map_into_boxed_body() /// .map_into_right_body(); /// /// Ok(ErrorHandlerResponse::Response(res)) /// } /// /// let app = App::new() /// .wrap(ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, add_error_body)) /// .service(web::resource("/").route(web::get().to(HttpResponse::InternalServerError))); /// ``` /// /// Registering default handler: /// /// ``` /// # use actix_web::{ /// # dev::ServiceResponse, /// # http::{header, StatusCode}, /// # middleware::{ErrorHandlerResponse, ErrorHandlers}, /// # web, App, HttpResponse, Result, /// # }; /// fn add_error_header<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { /// res.response_mut().headers_mut().insert( /// header::CONTENT_TYPE, /// header::HeaderValue::from_static("Error"), /// ); /// /// // body is unchanged, map to "left" slot /// Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) /// } /// /// fn handle_bad_request<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { /// res.response_mut().headers_mut().insert( /// header::CONTENT_TYPE, /// header::HeaderValue::from_static("Bad Request Error"), /// ); /// /// // body is unchanged, map to "left" slot /// Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) /// } /// /// // Bad Request errors will hit `handle_bad_request()`, while all other errors will hit /// // `add_error_header()`. The order in which the methods are called is not meaningful. /// let app = App::new() /// .wrap( /// ErrorHandlers::new() /// .default_handler(add_error_header) /// .handler(StatusCode::BAD_REQUEST, handle_bad_request) /// ) /// .service(web::resource("/").route(web::get().to(HttpResponse::InternalServerError))); /// ``` /// /// You can set default handlers for all client (4xx) or all server (5xx) errors: /// /// ``` /// # use actix_web::{ /// # dev::ServiceResponse, /// # http::{header, StatusCode}, /// # middleware::{ErrorHandlerResponse, ErrorHandlers}, /// # web, App, HttpResponse, Result, /// # }; /// # fn add_error_header<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { /// # res.response_mut().headers_mut().insert( /// # header::CONTENT_TYPE, /// # header::HeaderValue::from_static("Error"), /// # ); /// # Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) /// # } /// # fn handle_bad_request<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { /// # res.response_mut().headers_mut().insert( /// # header::CONTENT_TYPE, /// # header::HeaderValue::from_static("Bad Request Error"), /// # ); /// # Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) /// # } /// // Bad request errors will hit `handle_bad_request()`, other client errors will hit /// // `add_error_header()`, and server errors will pass through unchanged /// let app = App::new() /// .wrap( /// ErrorHandlers::new() /// .default_handler_client(add_error_header) // or .default_handler_server /// .handler(StatusCode::BAD_REQUEST, handle_bad_request) /// ) /// .service(web::resource("/").route(web::get().to(HttpResponse::InternalServerError))); /// ``` pub struct ErrorHandlers<B> { default_client: DefaultHandler<B>, default_server: DefaultHandler<B>, handlers: Handlers<B>, } type Handlers<B> = Rc<FoldHashMap<StatusCode, Box<ErrorHandler<B>>>>; impl<B> Default for ErrorHandlers<B> { fn default() -> Self { ErrorHandlers { default_client: Default::default(), default_server: Default::default(), handlers: Default::default(), } } } impl<B> ErrorHandlers<B> { /// Construct new `ErrorHandlers` instance. pub fn new() -> Self { ErrorHandlers::default() } /// Register error handler for specified status code. pub fn handler<F>(mut self, status: StatusCode, handler: F) -> Self where F: Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> + 'static, { Rc::get_mut(&mut self.handlers) .unwrap() .insert(status, Box::new(handler)); self } /// Register a default error handler. /// /// Any request with a status code that hasn't been given a specific other handler (by calling /// [`.handler()`][ErrorHandlers::handler]) will fall back on this. /// /// Note that this will overwrite any default handlers previously set by calling /// [`default_handler_client()`] or [`.default_handler_server()`], but not any set by calling /// [`.handler()`]. /// /// [`default_handler_client()`]: ErrorHandlers::default_handler_client /// [`.default_handler_server()`]: ErrorHandlers::default_handler_server /// [`.handler()`]: ErrorHandlers::handler pub fn default_handler<F>(self, handler: F) -> Self where F: Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> + 'static, { let handler = Rc::new(handler); let handler2 = Rc::clone(&handler); Self { default_server: Some(handler2), default_client: Some(handler), ..self } } /// Register a handler on which to fall back for client error status codes (400-499). pub fn default_handler_client<F>(self, handler: F) -> Self where F: Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> + 'static, { Self { default_client: Some(Rc::new(handler)), ..self } } /// Register a handler on which to fall back for server error status codes (500-599). pub fn default_handler_server<F>(self, handler: F) -> Self where F: Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> + 'static, { Self { default_server: Some(Rc::new(handler)), ..self } } /// Selects the most appropriate handler for the given status code. /// /// If the `handlers` map has an entry for that status code, that handler is returned. /// Otherwise, fall back on the appropriate default handler. fn get_handler<'a>( status: &StatusCode, default_client: Option<&'a ErrorHandler<B>>, default_server: Option<&'a ErrorHandler<B>>, handlers: &'a Handlers<B>, ) -> Option<&'a ErrorHandler<B>> { handlers .get(status) .map(|h| h.as_ref()) .or_else(|| status.is_client_error().then_some(default_client).flatten()) .or_else(|| status.is_server_error().then_some(default_server).flatten()) } } impl<S, B> Transform<S, ServiceRequest> for ErrorHandlers<B> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, S::Future: 'static, B: 'static, { type Response = ServiceResponse<EitherBody<B>>; type Error = Error; type Transform = ErrorHandlersMiddleware<S, B>; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { let handlers = Rc::clone(&self.handlers); let default_client = self.default_client.clone(); let default_server = self.default_server.clone(); Box::pin(async move { Ok(ErrorHandlersMiddleware { service, default_client, default_server, handlers, }) }) } } #[doc(hidden)] pub struct ErrorHandlersMiddleware<S, B> { service: S, default_client: DefaultHandler<B>, default_server: DefaultHandler<B>, handlers: Handlers<B>, } impl<S, B> Service<ServiceRequest> for ErrorHandlersMiddleware<S, B> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, B: 'static, { type Response = ServiceResponse<EitherBody<B>>; type Error = Error; type Future = ErrorHandlersFuture<S::Future, B>; actix_service::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { let handlers = Rc::clone(&self.handlers); let default_client = self.default_client.clone(); let default_server = self.default_server.clone(); let fut = self.service.call(req); ErrorHandlersFuture::ServiceFuture { fut, default_client, default_server, handlers, } } } pin_project! { #[project = ErrorHandlersProj] pub enum ErrorHandlersFuture<Fut, B> where Fut: Future, { ServiceFuture { #[pin] fut: Fut, default_client: DefaultHandler<B>, default_server: DefaultHandler<B>, handlers: Handlers<B>, }, ErrorHandlerFuture { fut: LocalBoxFuture<'static, Result<ServiceResponse<EitherBody<B>>, Error>>, }, } } impl<Fut, B> Future for ErrorHandlersFuture<Fut, B> where Fut: Future<Output = Result<ServiceResponse<B>, Error>>, { type Output = Result<ServiceResponse<EitherBody<B>>, Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { match self.as_mut().project() { ErrorHandlersProj::ServiceFuture { fut, default_client, default_server, handlers, } => { let res = ready!(fut.poll(cx))?; let status = res.status(); let handler = ErrorHandlers::get_handler( &status, default_client.as_mut().map(|f| Rc::as_ref(f)), default_server.as_mut().map(|f| Rc::as_ref(f)), handlers, ); match handler { Some(handler) => match handler(res)? { ErrorHandlerResponse::Response(res) => Poll::Ready(Ok(res)), ErrorHandlerResponse::Future(fut) => { self.as_mut() .set(ErrorHandlersFuture::ErrorHandlerFuture { fut }); self.poll(cx) } }, None => Poll::Ready(Ok(res.map_into_left_body())), } } ErrorHandlersProj::ErrorHandlerFuture { fut } => fut.as_mut().poll(cx), } } } #[cfg(test)] mod tests { use actix_service::IntoService; use actix_utils::future::ok; use bytes::Bytes; use futures_util::FutureExt as _; use super::*; use crate::{ body, http::header::{HeaderValue, CONTENT_TYPE}, test::{self, TestRequest}, }; #[actix_rt::test] async fn add_header_error_handler() { #[allow(clippy::unnecessary_wraps)] fn error_handler<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) } let srv = test::status_service(StatusCode::INTERNAL_SERVER_ERROR); let mw = ErrorHandlers::new() .handler(StatusCode::INTERNAL_SERVER_ERROR, error_handler) .new_transform(srv.into_service()) .await .unwrap(); let resp = test::call_service(&mw, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); } #[actix_rt::test] async fn add_header_error_handler_async() { #[allow(clippy::unnecessary_wraps)] fn error_handler<B: 'static>( mut res: ServiceResponse<B>, ) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(ErrorHandlerResponse::Future( ok(res.map_into_left_body()).boxed_local(), )) } let srv = test::status_service(StatusCode::INTERNAL_SERVER_ERROR); let mw = ErrorHandlers::new() .handler(StatusCode::INTERNAL_SERVER_ERROR, error_handler) .new_transform(srv.into_service()) .await .unwrap(); let resp = test::call_service(&mw, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); } #[actix_rt::test] async fn changes_body_type() { #[allow(clippy::unnecessary_wraps)] fn error_handler<B>(res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { let (req, res) = res.into_parts(); let res = res.set_body(Bytes::from("sorry, that's no bueno")); let res = ServiceResponse::new(req, res) .map_into_boxed_body() .map_into_right_body(); Ok(ErrorHandlerResponse::Response(res)) } let srv = test::status_service(StatusCode::INTERNAL_SERVER_ERROR); let mw = ErrorHandlers::new() .handler(StatusCode::INTERNAL_SERVER_ERROR, error_handler) .new_transform(srv.into_service()) .await .unwrap(); let res = test::call_service(&mw, TestRequest::default().to_srv_request()).await; assert_eq!(test::read_body(res).await, "sorry, that's no bueno"); } #[actix_rt::test] async fn error_thrown() { #[allow(clippy::unnecessary_wraps)] fn error_handler<B>(_res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { Err(crate::error::ErrorInternalServerError( "error in error handler", )) } let srv = test::status_service(StatusCode::BAD_REQUEST); let mw = ErrorHandlers::new() .handler(StatusCode::BAD_REQUEST, error_handler) .new_transform(srv.into_service()) .await .unwrap(); let err = mw .call(TestRequest::default().to_srv_request()) .await .unwrap_err(); let res = err.error_response(); assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR); assert_eq!( body::to_bytes(res.into_body()).await.unwrap(), "error in error handler" ); } #[actix_rt::test] async fn default_error_handler() { #[allow(clippy::unnecessary_wraps)] fn error_handler<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) } let make_mw = |status| async move { ErrorHandlers::new() .default_handler(error_handler) .new_transform(test::status_service(status).into_service()) .await .unwrap() }; let mw_server = make_mw(StatusCode::INTERNAL_SERVER_ERROR).await; let mw_client = make_mw(StatusCode::BAD_REQUEST).await; let resp = test::call_service(&mw_client, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); let resp = test::call_service(&mw_server, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); } #[actix_rt::test] async fn default_handlers_separate_client_server() { #[allow(clippy::unnecessary_wraps)] fn error_handler_client<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) } #[allow(clippy::unnecessary_wraps)] fn error_handler_server<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0002")); Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) } let make_mw = |status| async move { ErrorHandlers::new() .default_handler_server(error_handler_server) .default_handler_client(error_handler_client) .new_transform(test::status_service(status).into_service()) .await .unwrap() }; let mw_server = make_mw(StatusCode::INTERNAL_SERVER_ERROR).await; let mw_client = make_mw(StatusCode::BAD_REQUEST).await; let resp = test::call_service(&mw_client, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); let resp = test::call_service(&mw_server, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0002"); } #[actix_rt::test] async fn default_handlers_specialization() { #[allow(clippy::unnecessary_wraps)] fn error_handler_client<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) } #[allow(clippy::unnecessary_wraps)] fn error_handler_specific<B>( mut res: ServiceResponse<B>, ) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0003")); Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) } let make_mw = |status| async move { ErrorHandlers::new() .default_handler_client(error_handler_client) .handler(StatusCode::UNPROCESSABLE_ENTITY, error_handler_specific) .new_transform(test::status_service(status).into_service()) .await .unwrap() }; let mw_client = make_mw(StatusCode::BAD_REQUEST).await; let mw_specific = make_mw(StatusCode::UNPROCESSABLE_ENTITY).await; let resp = test::call_service(&mw_client, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); let resp = test::call_service(&mw_specific, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0003"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/compress.rs
actix-web/src/middleware/compress.rs
//! For middleware documentation, see [`Compress`]. use std::{ future::Future, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use actix_http::encoding::Encoder; use actix_service::{Service, Transform}; use actix_utils::future::{ok, Either, Ready}; use futures_core::ready; use mime::Mime; use once_cell::sync::Lazy; use pin_project_lite::pin_project; use crate::{ body::{EitherBody, MessageBody}, http::{ header::{self, AcceptEncoding, ContentEncoding, Encoding, HeaderValue}, StatusCode, }, service::{ServiceRequest, ServiceResponse}, Error, HttpMessage, HttpResponse, }; /// Middleware for compressing response payloads. /// /// # Encoding Negotiation /// `Compress` will read the `Accept-Encoding` header to negotiate which compression codec to use. /// Payloads are not compressed if the header is not sent. The `compress-*` [feature flags] are also /// considered in this selection process. /// /// # Pre-compressed Payload /// If you are serving some data that is already using a compressed representation (e.g., a gzip /// compressed HTML file from disk) you can signal this to `Compress` by setting an appropriate /// `Content-Encoding` header. In addition to preventing double compressing the payload, this header /// is required by the spec when using compressed representations and will inform the client that /// the content should be uncompressed. /// /// However, it is not advised to unconditionally serve encoded representations of content because /// the client may not support it. The [`AcceptEncoding`] typed header has some utilities to help /// perform manual encoding negotiation, if required. When negotiating content encoding, it is also /// required by the spec to send a `Vary: Accept-Encoding` header. /// /// A (naïve) example serving an pre-compressed Gzip file is included below. /// /// # Examples /// To enable automatic payload compression just include `Compress` as a top-level middleware: /// ``` /// use actix_web::{middleware, web, App, HttpResponse}; /// /// let app = App::new() /// .wrap(middleware::Compress::default()) /// .default_service(web::to(|| async { HttpResponse::Ok().body("hello world") })); /// ``` /// /// Pre-compressed Gzip file being served from disk with correct headers added to bypass middleware: /// ```no_run /// use actix_web::{middleware, http::header, web, App, HttpResponse, Responder}; /// /// async fn index_handler() -> actix_web::Result<impl Responder> { /// Ok(actix_files::NamedFile::open_async("./assets/index.html.gz").await? /// .customize() /// .insert_header(header::ContentEncoding::Gzip)) /// } /// /// let app = App::new() /// .wrap(middleware::Compress::default()) /// .default_service(web::to(index_handler)); /// ``` /// /// [feature flags]: ../index.html#crate-features #[derive(Debug, Clone, Default)] #[non_exhaustive] pub struct Compress; impl<S, B> Transform<S, ServiceRequest> for Compress where B: MessageBody, S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, { type Response = ServiceResponse<EitherBody<Encoder<B>>>; type Error = Error; type Transform = CompressMiddleware<S>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ok(CompressMiddleware { service }) } } pub struct CompressMiddleware<S> { service: S, } impl<S, B> Service<ServiceRequest> for CompressMiddleware<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, B: MessageBody, { type Response = ServiceResponse<EitherBody<Encoder<B>>>; type Error = Error; #[allow(clippy::type_complexity)] type Future = Either<CompressResponse<S, B>, Ready<Result<Self::Response, Self::Error>>>; actix_service::forward_ready!(service); #[allow(clippy::borrow_interior_mutable_const)] fn call(&self, req: ServiceRequest) -> Self::Future { // negotiate content-encoding let accept_encoding = req.get_header::<AcceptEncoding>(); let accept_encoding = match accept_encoding { // missing header; fallback to identity None => { return Either::left(CompressResponse { encoding: Encoding::identity(), fut: self.service.call(req), _phantom: PhantomData, }) } // valid accept-encoding header Some(accept_encoding) => accept_encoding, }; match accept_encoding.negotiate(SUPPORTED_ENCODINGS.iter()) { None => { let mut res = HttpResponse::with_body( StatusCode::NOT_ACCEPTABLE, SUPPORTED_ENCODINGS_STRING.as_str(), ); res.headers_mut() .insert(header::VARY, HeaderValue::from_static("Accept-Encoding")); Either::right(ok(req .into_response(res) .map_into_boxed_body() .map_into_right_body())) } Some(encoding) => Either::left(CompressResponse { fut: self.service.call(req), encoding, _phantom: PhantomData, }), } } } pin_project! { pub struct CompressResponse<S, B> where S: Service<ServiceRequest>, { #[pin] fut: S::Future, encoding: Encoding, _phantom: PhantomData<B>, } } impl<S, B> Future for CompressResponse<S, B> where B: MessageBody, S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, { type Output = Result<ServiceResponse<EitherBody<Encoder<B>>>, Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.as_mut().project(); match ready!(this.fut.poll(cx)) { Ok(resp) => { let enc = match this.encoding { Encoding::Known(enc) => *enc, Encoding::Unknown(enc) => { unimplemented!("encoding '{enc}' should not be here"); } }; Poll::Ready(Ok(resp.map_body(move |head, body| { let content_type = head.headers.get(header::CONTENT_TYPE); fn default_compress_predicate(content_type: Option<&HeaderValue>) -> bool { match content_type { None => true, Some(hdr) => { match hdr.to_str().ok().and_then(|hdr| hdr.parse::<Mime>().ok()) { Some(mime) if mime.type_() == mime::IMAGE => { matches!(mime.subtype(), mime::SVG) } Some(mime) if mime.type_() == mime::VIDEO => false, _ => true, } } } } let enc = if default_compress_predicate(content_type) { enc } else { ContentEncoding::Identity }; EitherBody::left(Encoder::response(enc, head, body)) }))) } Err(err) => Poll::Ready(Err(err)), } } } static SUPPORTED_ENCODINGS_STRING: Lazy<String> = Lazy::new(|| { #[allow(unused_mut)] // only unused when no compress features enabled let mut encoding: Vec<&str> = vec![]; #[cfg(feature = "compress-brotli")] { encoding.push("br"); } #[cfg(feature = "compress-gzip")] { encoding.push("gzip"); encoding.push("deflate"); } #[cfg(feature = "compress-zstd")] { encoding.push("zstd"); } assert!( !encoding.is_empty(), "encoding can not be empty unless __compress feature has been explicitly enabled by itself" ); encoding.join(", ") }); static SUPPORTED_ENCODINGS: &[Encoding] = &[ Encoding::identity(), #[cfg(feature = "compress-brotli")] { Encoding::brotli() }, #[cfg(feature = "compress-gzip")] { Encoding::gzip() }, #[cfg(feature = "compress-gzip")] { Encoding::deflate() }, #[cfg(feature = "compress-zstd")] { Encoding::zstd() }, ]; // move cfg(feature) to prevents_double_compressing if more tests are added #[cfg(feature = "compress-gzip")] #[cfg(test)] mod tests { use std::collections::HashSet; use static_assertions::assert_impl_all; use super::*; use crate::{http::header::ContentType, middleware::DefaultHeaders, test, web, App}; const HTML_DATA_PART: &str = "<html><h1>hello world</h1></html"; const HTML_DATA: &str = const_str::repeat!(HTML_DATA_PART, 100); const TEXT_DATA_PART: &str = "hello world "; const TEXT_DATA: &str = const_str::repeat!(TEXT_DATA_PART, 100); assert_impl_all!(Compress: Send, Sync); pub fn gzip_decode(bytes: impl AsRef<[u8]>) -> Vec<u8> { use std::io::Read as _; let mut decoder = flate2::read::GzDecoder::new(bytes.as_ref()); let mut buf = Vec::new(); decoder.read_to_end(&mut buf).unwrap(); buf } #[track_caller] fn assert_successful_res_with_content_type<B>(res: &ServiceResponse<B>, ct: &str) { assert!(res.status().is_success()); assert!( res.headers() .get(header::CONTENT_TYPE) .expect("content-type header should be present") .to_str() .expect("content-type header should be utf-8") .contains(ct), "response's content-type did not match {}", ct ); } #[track_caller] fn assert_successful_gzip_res_with_content_type<B>(res: &ServiceResponse<B>, ct: &str) { assert_successful_res_with_content_type(res, ct); assert_eq!( res.headers() .get(header::CONTENT_ENCODING) .expect("response should be gzip compressed"), "gzip", ); } #[track_caller] fn assert_successful_identity_res_with_content_type<B>(res: &ServiceResponse<B>, ct: &str) { assert_successful_res_with_content_type(res, ct); assert!( res.headers().get(header::CONTENT_ENCODING).is_none(), "response should not be compressed", ); } #[actix_rt::test] async fn prevents_double_compressing() { let app = test::init_service({ App::new() .wrap(Compress::default()) .route( "/single", web::get().to(move || HttpResponse::Ok().body(TEXT_DATA)), ) .service( web::resource("/double") .wrap(Compress::default()) .wrap(DefaultHeaders::new().add(("x-double", "true"))) .route(web::get().to(move || HttpResponse::Ok().body(TEXT_DATA))), ) }) .await; let req = test::TestRequest::default() .uri("/single") .insert_header((header::ACCEPT_ENCODING, "gzip")) .to_request(); let res = test::call_service(&app, req).await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.headers().get("x-double"), None); assert_eq!(res.headers().get(header::CONTENT_ENCODING).unwrap(), "gzip"); let bytes = test::read_body(res).await; assert_eq!(gzip_decode(bytes), TEXT_DATA.as_bytes()); let req = test::TestRequest::default() .uri("/double") .insert_header((header::ACCEPT_ENCODING, "gzip")) .to_request(); let res = test::call_service(&app, req).await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.headers().get("x-double").unwrap(), "true"); assert_eq!(res.headers().get(header::CONTENT_ENCODING).unwrap(), "gzip"); let bytes = test::read_body(res).await; assert_eq!(gzip_decode(bytes), TEXT_DATA.as_bytes()); } #[actix_rt::test] async fn retains_previously_set_vary_header() { let app = test::init_service({ App::new() .wrap(Compress::default()) .default_service(web::to(move || { HttpResponse::Ok() .insert_header((header::VARY, "x-test")) .body(TEXT_DATA) })) }) .await; let req = test::TestRequest::default() .insert_header((header::ACCEPT_ENCODING, "gzip")) .to_request(); let res = test::call_service(&app, req).await; assert_eq!(res.status(), StatusCode::OK); #[allow(clippy::mutable_key_type)] let vary_headers = res.headers().get_all(header::VARY).collect::<HashSet<_>>(); assert!(vary_headers.contains(&HeaderValue::from_static("x-test"))); assert!(vary_headers.contains(&HeaderValue::from_static("accept-encoding"))); } fn configure_predicate_test(cfg: &mut web::ServiceConfig) { cfg.route( "/html", web::get().to(|| { HttpResponse::Ok() .content_type(ContentType::html()) .body(HTML_DATA) }), ) .route( "/image", web::get().to(|| { HttpResponse::Ok() .content_type(ContentType::jpeg()) .body(TEXT_DATA) }), ); } #[actix_rt::test] async fn prevents_compression_jpeg() { let app = test::init_service( App::new() .wrap(Compress::default()) .configure(configure_predicate_test), ) .await; let req = test::TestRequest::with_uri("/html").insert_header((header::ACCEPT_ENCODING, "gzip")); let res = test::call_service(&app, req.to_request()).await; assert_successful_gzip_res_with_content_type(&res, "text/html"); assert_ne!(test::read_body(res).await, HTML_DATA.as_bytes()); let req = test::TestRequest::with_uri("/image").insert_header((header::ACCEPT_ENCODING, "gzip")); let res = test::call_service(&app, req.to_request()).await; assert_successful_identity_res_with_content_type(&res, "image/jpeg"); assert_eq!(test::read_body(res).await, TEXT_DATA.as_bytes()); } #[actix_rt::test] async fn prevents_compression_empty() { let app = test::init_service({ App::new() .wrap(Compress::default()) .default_service(web::to(move || HttpResponse::Ok().finish())) }) .await; let req = test::TestRequest::default() .insert_header((header::ACCEPT_ENCODING, "gzip")) .to_request(); let res = test::call_service(&app, req).await; assert_eq!(res.status(), StatusCode::OK); assert!(!res.headers().contains_key(header::CONTENT_ENCODING)); assert!(test::read_body(res).await.is_empty()); } } #[cfg(feature = "compress-brotli")] #[cfg(test)] mod tests_brotli { use super::*; use crate::{test, web, App}; #[actix_rt::test] async fn prevents_compression_empty() { let app = test::init_service({ App::new() .wrap(Compress::default()) .default_service(web::to(move || HttpResponse::Ok().finish())) }) .await; let req = test::TestRequest::default() .insert_header((header::ACCEPT_ENCODING, "br")) .to_request(); let res = test::call_service(&app, req).await; assert_eq!(res.status(), StatusCode::OK); assert!(!res.headers().contains_key(header::CONTENT_ENCODING)); assert!(test::read_body(res).await.is_empty()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/logger.rs
actix-web/src/middleware/logger.rs
//! For middleware documentation, see [`Logger`]. use std::{ borrow::Cow, collections::HashSet, env, fmt::{self, Display as _}, future::Future, marker::PhantomData, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_service::{Service, Transform}; use actix_utils::future::{ready, Ready}; use bytes::Bytes; use futures_core::ready; use log::{debug, warn, Level}; use pin_project_lite::pin_project; #[cfg(feature = "unicode")] use regex::Regex; #[cfg(not(feature = "unicode"))] use regex_lite::Regex; use time::{format_description::well_known::Rfc3339, OffsetDateTime}; use crate::{ body::{BodySize, MessageBody}, http::header::HeaderName, service::{ServiceRequest, ServiceResponse}, Error, Result, }; /// Middleware for logging request and response summaries to the terminal. /// /// This middleware uses the `log` crate to output information. Enable `log`'s output for the /// "actix_web" scope using [`env_logger`](https://docs.rs/env_logger) or similar crate. /// /// # Default Format /// The [`default`](Logger::default) Logger uses the following format: /// /// ```plain /// %a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T /// /// Example Output: /// 127.0.0.1:54278 "GET /test HTTP/1.1" 404 20 "-" "HTTPie/2.2.0" 0.001074 /// ``` /// /// # Examples /// ``` /// use actix_web::{middleware::Logger, App}; /// /// // access logs are printed with the INFO level so ensure it is enabled by default /// env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); /// /// let app = App::new() /// // .wrap(Logger::default()) /// .wrap(Logger::new("%a %{User-Agent}i")); /// ``` /// /// # Format /// Variable | Description /// -------- | ----------- /// `%%` | The percent sign /// `%a` | Peer IP address (or IP address of reverse proxy if used) /// `%t` | Time when the request started processing (in RFC 3339 format) /// `%r` | First line of request (Example: `GET /test HTTP/1.1`) /// `%s` | Response status code /// `%b` | Size of response in bytes, including HTTP headers /// `%T` | Time taken to serve the request, in seconds to 6 decimal places /// `%D` | Time taken to serve the request, in milliseconds /// `%U` | Request URL /// `%{r}a` | "Real IP" remote address **\*** /// `%{FOO}i` | `request.headers["FOO"]` /// `%{FOO}o` | `response.headers["FOO"]` /// `%{FOO}e` | `env_var["FOO"]` /// `%{FOO}xi` | [Custom request replacement](Logger::custom_request_replace) labelled "FOO" /// `%{FOO}xo` | [Custom response replacement](Logger::custom_response_replace) labelled "FOO" /// /// # Security /// **\*** "Real IP" remote address is calculated using /// [`ConnectionInfo::realip_remote_addr()`](crate::dev::ConnectionInfo::realip_remote_addr()) /// /// If you use this value, ensure that all requests come from trusted hosts. Otherwise, it is /// trivial for the remote client to falsify their source IP address. #[derive(Debug)] pub struct Logger(Rc<Inner>); #[derive(Debug, Clone)] struct Inner { format: Format, exclude: HashSet<String>, exclude_regex: Vec<Regex>, log_target: Cow<'static, str>, log_level: Level, } impl Logger { /// Create `Logger` middleware with the specified `format`. pub fn new(format: &str) -> Logger { Logger(Rc::new(Inner { format: Format::new(format), exclude: HashSet::new(), exclude_regex: Vec::new(), log_target: Cow::Borrowed(module_path!()), log_level: Level::Info, })) } /// Ignore and do not log access info for specified path. pub fn exclude<T: Into<String>>(mut self, path: T) -> Self { Rc::get_mut(&mut self.0) .unwrap() .exclude .insert(path.into()); self } /// Ignore and do not log access info for paths that match regex. pub fn exclude_regex<T: Into<String>>(mut self, path: T) -> Self { let inner = Rc::get_mut(&mut self.0).unwrap(); inner.exclude_regex.push(Regex::new(&path.into()).unwrap()); self } /// Sets the logging target to `target`. /// /// By default, the log target is `module_path!()` of the log call location. In our case, that /// would be `actix_web::middleware::logger`. /// /// # Examples /// Using `.log_target("http_log")` would have this effect on request logs: /// ```diff /// - [2015-10-21T07:28:00Z INFO actix_web::middleware::logger] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985 /// + [2015-10-21T07:28:00Z INFO http_log] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985 /// ^^^^^^^^ /// ``` pub fn log_target(mut self, target: impl Into<Cow<'static, str>>) -> Self { let inner = Rc::get_mut(&mut self.0).unwrap(); inner.log_target = target.into(); self } /// Sets the log level to `level`. /// /// By default, the log level is `Level::Info`. /// /// # Examples /// Using `.log_level(Level::Debug)` would have this effect on request logs: /// ```diff /// - [2015-10-21T07:28:00Z INFO actix_web::middleware::logger] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985 /// + [2015-10-21T07:28:00Z DEBUG actix_web::middleware::logger] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985 /// ^^^^^^ /// ``` pub fn log_level(mut self, level: log::Level) -> Self { let inner = Rc::get_mut(&mut self.0).unwrap(); inner.log_level = level; self } /// Register a function that receives a ServiceRequest and returns a String for use in the /// log line. The label passed as the first argument should match a replacement substring in /// the logger format like `%{label}xi`. /// /// It is convention to print "-" to indicate no output instead of an empty string. /// /// # Examples /// ``` /// # use actix_web::http::{header::HeaderValue}; /// # use actix_web::middleware::Logger; /// # fn parse_jwt_id (_req: Option<&HeaderValue>) -> String { "jwt_uid".to_owned() } /// Logger::new("example %{JWT_ID}xi") /// .custom_request_replace("JWT_ID", |req| parse_jwt_id(req.headers().get("Authorization"))); /// ``` pub fn custom_request_replace( mut self, label: &str, f: impl Fn(&ServiceRequest) -> String + 'static, ) -> Self { let inner = Rc::get_mut(&mut self.0).unwrap(); let ft = inner.format.0.iter_mut().find( |ft| matches!(ft, FormatText::CustomRequest(unit_label, _) if label == unit_label), ); if let Some(FormatText::CustomRequest(_, request_fn)) = ft { // replace into None or previously registered fn using same label request_fn.replace(CustomRequestFn { inner_fn: Rc::new(f), }); } else { // non-printed request replacement function diagnostic debug!( "Attempted to register custom request logging function for nonexistent label: {}", label ); } self } /// Register a function that receives a `ServiceResponse` and returns a string for use in the /// log line. /// /// The label passed as the first argument should match a replacement substring in /// the logger format like `%{label}xo`. /// /// It is convention to print "-" to indicate no output instead of an empty string. /// /// The replacement function does not have access to the response body. /// /// # Examples /// ``` /// # use actix_web::{dev::ServiceResponse, middleware::Logger}; /// fn log_if_error(res: &ServiceResponse) -> String { /// if res.status().as_u16() >= 400 { /// "ERROR".to_string() /// } else { /// "-".to_string() /// } /// } /// /// Logger::new("example %{ERROR_STATUS}xo") /// .custom_response_replace("ERROR_STATUS", |res| log_if_error(res) ); /// ``` pub fn custom_response_replace( mut self, label: &str, f: impl Fn(&ServiceResponse) -> String + 'static, ) -> Self { let inner = Rc::get_mut(&mut self.0).unwrap(); let ft = inner.format.0.iter_mut().find( |ft| matches!(ft, FormatText::CustomResponse(unit_label, _) if label == unit_label), ); if let Some(FormatText::CustomResponse(_, res_fn)) = ft { *res_fn = Some(CustomResponseFn { inner_fn: Rc::new(f), }); } else { debug!( "Attempted to register custom response logging function for non-existent label: {}", label ); } self } } impl Default for Logger { /// Create `Logger` middleware with format: /// /// ```plain /// %a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T /// ``` fn default() -> Logger { Logger(Rc::new(Inner { format: Format::default(), exclude: HashSet::new(), exclude_regex: Vec::new(), log_target: Cow::Borrowed(module_path!()), log_level: Level::Info, })) } } impl<S, B> Transform<S, ServiceRequest> for Logger where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, B: MessageBody, { type Response = ServiceResponse<StreamLog<B>>; type Error = Error; type Transform = LoggerMiddleware<S>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { for unit in &self.0.format.0 { if let FormatText::CustomRequest(label, None) = unit { warn!( "No custom request replacement function was registered for label: {}", label ); } if let FormatText::CustomResponse(label, None) = unit { warn!( "No custom response replacement function was registered for label: {}", label ); } } ready(Ok(LoggerMiddleware { service, inner: Rc::clone(&self.0), })) } } /// Logger middleware service. pub struct LoggerMiddleware<S> { inner: Rc<Inner>, service: S, } impl<S, B> Service<ServiceRequest> for LoggerMiddleware<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, B: MessageBody, { type Response = ServiceResponse<StreamLog<B>>; type Error = Error; type Future = LoggerResponse<S, B>; actix_service::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { let excluded = self.inner.exclude.contains(req.path()) || self .inner .exclude_regex .iter() .any(|r| r.is_match(req.path())); if excluded { LoggerResponse { fut: self.service.call(req), format: None, time: OffsetDateTime::now_utc(), log_target: Cow::Borrowed(""), log_level: self.inner.log_level, _phantom: PhantomData, } } else { let now = OffsetDateTime::now_utc(); let mut format = self.inner.format.clone(); for unit in &mut format.0 { unit.render_request(now, &req); } LoggerResponse { fut: self.service.call(req), format: Some(format), time: now, log_target: self.inner.log_target.clone(), log_level: self.inner.log_level, _phantom: PhantomData, } } } } pin_project! { pub struct LoggerResponse<S, B> where B: MessageBody, S: Service<ServiceRequest>, { #[pin] fut: S::Future, time: OffsetDateTime, format: Option<Format>, log_target: Cow<'static, str>, log_level: Level, _phantom: PhantomData<B>, } } impl<S, B> Future for LoggerResponse<S, B> where B: MessageBody, S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, { type Output = Result<ServiceResponse<StreamLog<B>>, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let res = match ready!(this.fut.poll(cx)) { Ok(res) => res, Err(err) => return Poll::Ready(Err(err)), }; if let Some(error) = res.response().error() { debug!("Error in response: {:?}", error); } let res = if let Some(ref mut format) = this.format { // to avoid polluting all the Logger types with the body parameter we swap the body // out temporarily since it's not usable in custom response functions anyway let (req, res) = res.into_parts(); let (res, body) = res.into_parts(); let temp_res = ServiceResponse::new(req, res.map_into_boxed_body()); for unit in &mut format.0 { unit.render_response(&temp_res); } // re-construct original service response let (req, res) = temp_res.into_parts(); ServiceResponse::new(req, res.set_body(body)) } else { res }; let time = *this.time; let format = this.format.take(); let log_target = this.log_target.clone(); let log_level = *this.log_level; Poll::Ready(Ok(res.map_body(move |_, body| StreamLog { body, time, format, size: 0, log_target, log_level, }))) } } pin_project! { pub struct StreamLog<B> { #[pin] body: B, format: Option<Format>, size: usize, time: OffsetDateTime, log_target: Cow<'static, str>, log_level: Level } impl<B> PinnedDrop for StreamLog<B> { fn drop(this: Pin<&mut Self>) { if let Some(ref format) = this.format { let render = |fmt: &mut fmt::Formatter<'_>| { for unit in &format.0 { unit.render(fmt, this.size, this.time)?; } Ok(()) }; log::log!( target: this.log_target.as_ref(), this.log_level, "{}", FormatDisplay(&render) ); } } } } impl<B: MessageBody> MessageBody for StreamLog<B> { type Error = B::Error; #[inline] fn size(&self) -> BodySize { self.body.size() } fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Bytes, Self::Error>>> { let this = self.project(); match ready!(this.body.poll_next(cx)) { Some(Ok(chunk)) => { *this.size += chunk.len(); Poll::Ready(Some(Ok(chunk))) } Some(Err(err)) => Poll::Ready(Some(Err(err))), None => Poll::Ready(None), } } } /// A formatting style for the `Logger` consisting of multiple concatenated `FormatText` items. #[derive(Debug, Clone)] struct Format(Vec<FormatText>); impl Default for Format { /// Return the default formatting style for the `Logger`: fn default() -> Format { Format::new(r#"%a "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T"#) } } impl Format { /// Create a `Format` from a format string. /// /// Returns `None` if the format string syntax is incorrect. pub fn new(s: &str) -> Format { log::trace!("Access log format: {}", s); let fmt = Regex::new(r"%(\{([A-Za-z0-9\-_]+)\}([aioe]|x[io])|[%atPrUsbTD]?)").unwrap(); let mut idx = 0; let mut results = Vec::new(); for cap in fmt.captures_iter(s) { let m = cap.get(0).unwrap(); let pos = m.start(); if idx != pos { results.push(FormatText::Str(s[idx..pos].to_owned())); } idx = m.end(); if let Some(key) = cap.get(2) { results.push(match cap.get(3).unwrap().as_str() { "a" => { if key.as_str() == "r" { FormatText::RealIpRemoteAddr } else { unreachable!("regex and code mismatch") } } "i" => FormatText::RequestHeader(HeaderName::try_from(key.as_str()).unwrap()), "o" => FormatText::ResponseHeader(HeaderName::try_from(key.as_str()).unwrap()), "e" => FormatText::EnvironHeader(key.as_str().to_owned()), "xi" => FormatText::CustomRequest(key.as_str().to_owned(), None), "xo" => FormatText::CustomResponse(key.as_str().to_owned(), None), _ => unreachable!(), }) } else { let m = cap.get(1).unwrap(); results.push(match m.as_str() { "%" => FormatText::Percent, "a" => FormatText::RemoteAddr, "t" => FormatText::RequestTime, "r" => FormatText::RequestLine, "s" => FormatText::ResponseStatus, "b" => FormatText::ResponseSize, "U" => FormatText::UrlPath, "T" => FormatText::Time, "D" => FormatText::TimeMillis, _ => FormatText::Str(m.as_str().to_owned()), }); } } if idx != s.len() { results.push(FormatText::Str(s[idx..].to_owned())); } Format(results) } } /// A string of text to be logged. /// /// This is either one of the data fields supported by the `Logger`, or a custom `String`. #[non_exhaustive] #[derive(Debug, Clone)] enum FormatText { Str(String), Percent, RequestLine, RequestTime, ResponseStatus, ResponseSize, Time, TimeMillis, RemoteAddr, RealIpRemoteAddr, UrlPath, RequestHeader(HeaderName), ResponseHeader(HeaderName), EnvironHeader(String), CustomRequest(String, Option<CustomRequestFn>), CustomResponse(String, Option<CustomResponseFn>), } #[derive(Clone)] struct CustomRequestFn { inner_fn: Rc<dyn Fn(&ServiceRequest) -> String>, } impl CustomRequestFn { fn call(&self, req: &ServiceRequest) -> String { (self.inner_fn)(req) } } impl fmt::Debug for CustomRequestFn { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("custom_request_fn") } } #[derive(Clone)] struct CustomResponseFn { inner_fn: Rc<dyn Fn(&ServiceResponse) -> String>, } impl CustomResponseFn { fn call(&self, res: &ServiceResponse) -> String { (self.inner_fn)(res) } } impl fmt::Debug for CustomResponseFn { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("custom_response_fn") } } impl FormatText { fn render( &self, fmt: &mut fmt::Formatter<'_>, size: usize, entry_time: OffsetDateTime, ) -> Result<(), fmt::Error> { match self { FormatText::Str(ref string) => fmt.write_str(string), FormatText::Percent => "%".fmt(fmt), FormatText::ResponseSize => size.fmt(fmt), FormatText::Time => { let rt = OffsetDateTime::now_utc() - entry_time; let rt = rt.as_seconds_f64(); fmt.write_fmt(format_args!("{:.6}", rt)) } FormatText::TimeMillis => { let rt = OffsetDateTime::now_utc() - entry_time; let rt = (rt.whole_nanoseconds() as f64) / 1_000_000.0; fmt.write_fmt(format_args!("{:.6}", rt)) } FormatText::EnvironHeader(ref name) => { if let Ok(val) = env::var(name) { fmt.write_fmt(format_args!("{}", val)) } else { "-".fmt(fmt) } } _ => Ok(()), } } fn render_response(&mut self, res: &ServiceResponse) { match self { FormatText::ResponseStatus => { *self = FormatText::Str(format!("{}", res.status().as_u16())) } FormatText::ResponseHeader(ref name) => { let s = if let Some(val) = res.headers().get(name) { String::from_utf8_lossy(val.as_bytes()).into_owned() } else { "-".to_owned() }; *self = FormatText::Str(s.to_string()) } FormatText::CustomResponse(_, res_fn) => { let text = match res_fn { Some(res_fn) => FormatText::Str(res_fn.call(res)), None => FormatText::Str("-".to_owned()), }; *self = text; } _ => {} } } fn render_request(&mut self, now: OffsetDateTime, req: &ServiceRequest) { match self { FormatText::RequestLine => { *self = if req.query_string().is_empty() { FormatText::Str(format!( "{} {} {:?}", req.method(), req.path(), req.version() )) } else { FormatText::Str(format!( "{} {}?{} {:?}", req.method(), req.path(), req.query_string(), req.version() )) }; } FormatText::UrlPath => *self = FormatText::Str(req.path().to_string()), FormatText::RequestTime => *self = FormatText::Str(now.format(&Rfc3339).unwrap()), FormatText::RequestHeader(ref name) => { let s = if let Some(val) = req.headers().get(name) { String::from_utf8_lossy(val.as_bytes()).into_owned() } else { "-".to_owned() }; *self = FormatText::Str(s); } FormatText::RemoteAddr => { let s = if let Some(peer) = req.connection_info().peer_addr() { FormatText::Str((*peer).to_string()) } else { FormatText::Str("-".to_string()) }; *self = s; } FormatText::RealIpRemoteAddr => { let s = if let Some(remote) = req.connection_info().realip_remote_addr() { FormatText::Str(remote.to_string()) } else { FormatText::Str("-".to_string()) }; *self = s; } FormatText::CustomRequest(_, request_fn) => { let s = match request_fn { Some(f) => FormatText::Str(f.call(req)), None => FormatText::Str("-".to_owned()), }; *self = s; } _ => {} } } } /// Converter to get a String from something that writes to a Formatter. pub(crate) struct FormatDisplay<'a>(&'a dyn Fn(&mut fmt::Formatter<'_>) -> Result<(), fmt::Error>); impl fmt::Display for FormatDisplay<'_> { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { (self.0)(fmt) } } #[cfg(test)] mod tests { use actix_service::IntoService; use actix_utils::future::ok; use super::*; use crate::{ http::{header, StatusCode}, test::{self, TestRequest}, HttpResponse, }; #[actix_rt::test] async fn test_logger() { let srv = |req: ServiceRequest| { ok(req.into_response( HttpResponse::build(StatusCode::OK) .insert_header(("X-Test", "ttt")) .finish(), )) }; let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test"); let srv = logger.new_transform(srv.into_service()).await.unwrap(); let req = TestRequest::default() .insert_header(( header::USER_AGENT, header::HeaderValue::from_static("ACTIX-WEB"), )) .to_srv_request(); let _res = srv.call(req).await; } #[actix_rt::test] async fn test_logger_exclude_regex() { let srv = |req: ServiceRequest| { ok(req.into_response( HttpResponse::build(StatusCode::OK) .insert_header(("X-Test", "ttt")) .finish(), )) }; let logger = Logger::new("%% %{User-Agent}i %{X-Test}o %{HOME}e %D test").exclude_regex("\\w"); let srv = logger.new_transform(srv.into_service()).await.unwrap(); let req = TestRequest::default() .insert_header(( header::USER_AGENT, header::HeaderValue::from_static("ACTIX-WEB"), )) .to_srv_request(); let _res = srv.call(req).await.unwrap(); } #[actix_rt::test] async fn test_escape_percent() { let mut format = Format::new("%%{r}a"); let req = TestRequest::default() .insert_header(( header::FORWARDED, header::HeaderValue::from_static("for=192.0.2.60;proto=http;by=203.0.113.43"), )) .to_srv_request(); let now = OffsetDateTime::now_utc(); for unit in &mut format.0 { unit.render_request(now, &req); } let req = TestRequest::default().to_http_request(); let res = ServiceResponse::new(req, HttpResponse::Ok().finish()); for unit in &mut format.0 { unit.render_response(&res); } let entry_time = OffsetDateTime::now_utc(); let render = |fmt: &mut fmt::Formatter<'_>| { for unit in &format.0 { unit.render(fmt, 1024, entry_time)?; } Ok(()) }; let s = format!("{}", FormatDisplay(&render)); assert_eq!(s, "%{r}a"); } #[actix_rt::test] async fn test_url_path() { let mut format = Format::new("%T %U"); let req = TestRequest::default() .insert_header(( header::USER_AGENT, header::HeaderValue::from_static("ACTIX-WEB"), )) .uri("/test/route/yeah") .to_srv_request(); let now = OffsetDateTime::now_utc(); for unit in &mut format.0 { unit.render_request(now, &req); } let req = TestRequest::default().to_http_request(); let res = ServiceResponse::new(req, HttpResponse::Ok().force_close().finish()); for unit in &mut format.0 { unit.render_response(&res); } let render = |fmt: &mut fmt::Formatter<'_>| { for unit in &format.0 { unit.render(fmt, 1024, now)?; } Ok(()) }; let s = format!("{}", FormatDisplay(&render)); assert!(s.contains("/test/route/yeah")); } #[actix_rt::test] async fn test_default_format() { let mut format = Format::default(); let req = TestRequest::default() .insert_header(( header::USER_AGENT, header::HeaderValue::from_static("ACTIX-WEB"), )) .peer_addr("127.0.0.1:8081".parse().unwrap()) .to_srv_request(); let now = OffsetDateTime::now_utc(); for unit in &mut format.0 { unit.render_request(now, &req); } let req = TestRequest::default().to_http_request(); let res = ServiceResponse::new(req, HttpResponse::Ok().force_close().finish()); for unit in &mut format.0 { unit.render_response(&res); } let entry_time = OffsetDateTime::now_utc(); let render = |fmt: &mut fmt::Formatter<'_>| { for unit in &format.0 { unit.render(fmt, 1024, entry_time)?; } Ok(()) }; let s = format!("{}", FormatDisplay(&render)); assert!(s.contains("GET / HTTP/1.1")); assert!(s.contains("127.0.0.1")); assert!(s.contains("200 1024")); assert!(s.contains("ACTIX-WEB")); } #[actix_rt::test] async fn test_request_time_format() { let mut format = Format::new("%t"); let req = TestRequest::default().to_srv_request(); let now = OffsetDateTime::now_utc(); for unit in &mut format.0 { unit.render_request(now, &req); } let req = TestRequest::default().to_http_request(); let res = ServiceResponse::new(req, HttpResponse::Ok().force_close().finish()); for unit in &mut format.0 { unit.render_response(&res); } let render = |fmt: &mut fmt::Formatter<'_>| { for unit in &format.0 { unit.render(fmt, 1024, now)?; } Ok(()) }; let s = format!("{}", FormatDisplay(&render)); assert!(s.contains(&now.format(&Rfc3339).unwrap())); } #[actix_rt::test] async fn test_remote_addr_format() { let mut format = Format::new("%{r}a"); let req = TestRequest::default() .insert_header(( header::FORWARDED, header::HeaderValue::from_static("for=192.0.2.60;proto=http;by=203.0.113.43"), )) .to_srv_request(); let now = OffsetDateTime::now_utc(); for unit in &mut format.0 { unit.render_request(now, &req); } let req = TestRequest::default().to_http_request(); let res = ServiceResponse::new(req, HttpResponse::Ok().finish()); for unit in &mut format.0 { unit.render_response(&res); } let entry_time = OffsetDateTime::now_utc(); let render = |fmt: &mut fmt::Formatter<'_>| { for unit in &format.0 { unit.render(fmt, 1024, entry_time)?; } Ok(()) }; let s = format!("{}", FormatDisplay(&render)); assert!(s.contains("192.0.2.60")); } #[actix_rt::test] async fn test_custom_closure_req_log() { let mut logger = Logger::new("test %{CUSTOM}xi") .custom_request_replace("CUSTOM", |_req: &ServiceRequest| -> String { String::from("custom_log") }); let mut unit = Rc::get_mut(&mut logger.0).unwrap().format.0[1].clone(); let label = match &unit { FormatText::CustomRequest(label, _) => label, ft => panic!("expected CustomRequest, found {:?}", ft), }; assert_eq!(label, "CUSTOM"); let req = TestRequest::default().to_srv_request(); let now = OffsetDateTime::now_utc(); unit.render_request(now, &req); let render = |fmt: &mut fmt::Formatter<'_>| unit.render(fmt, 1024, now); let log_output = FormatDisplay(&render).to_string(); assert_eq!(log_output, "custom_log"); } #[actix_rt::test] async fn test_custom_closure_response_log() { let mut logger = Logger::new("test %{CUSTOM}xo").custom_response_replace( "CUSTOM", |res: &ServiceResponse| -> String { if res.status().as_u16() == 200 { String::from("custom_log") } else { String::from("-") } }, ); let mut unit = Rc::get_mut(&mut logger.0).unwrap().format.0[1].clone(); let label = match &unit { FormatText::CustomResponse(label, _) => label, ft => panic!("expected CustomResponse, found {:?}", ft), }; assert_eq!(label, "CUSTOM"); let req = TestRequest::default().to_http_request(); let resp_ok = ServiceResponse::new(req, HttpResponse::Ok().finish()); let now = OffsetDateTime::now_utc(); unit.render_response(&resp_ok);
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
true
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/from_fn.rs
actix-web/src/middleware/from_fn.rs
use std::{future::Future, marker::PhantomData, rc::Rc}; use actix_service::boxed::{self, BoxFuture, RcService}; use actix_utils::future::{ready, Ready}; use futures_core::future::LocalBoxFuture; use crate::{ body::MessageBody, dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform}, Error, FromRequest, }; /// Wraps an async function to be used as a middleware. /// /// # Examples /// /// The wrapped function should have the following form: /// /// ``` /// # use actix_web::{ /// # App, Error, /// # body::MessageBody, /// # dev::{ServiceRequest, ServiceResponse, Service as _}, /// # }; /// use actix_web::middleware::{self, Next}; /// /// async fn my_mw( /// req: ServiceRequest, /// next: Next<impl MessageBody>, /// ) -> Result<ServiceResponse<impl MessageBody>, Error> { /// // pre-processing /// next.call(req).await /// // post-processing /// } /// # App::new().wrap(middleware::from_fn(my_mw)); /// ``` /// /// Then use in an app builder like this: /// /// ``` /// use actix_web::{ /// App, Error, /// dev::{ServiceRequest, ServiceResponse, Service as _}, /// }; /// use actix_web::middleware::from_fn; /// # use actix_web::middleware::Next; /// # async fn my_mw<B>(req: ServiceRequest, next: Next<B>) -> Result<ServiceResponse<B>, Error> { /// # next.call(req).await /// # } /// /// App::new() /// .wrap(from_fn(my_mw)) /// # ; /// ``` /// /// It is also possible to write a middleware that automatically uses extractors, similar to request /// handlers, by declaring them as the first parameters. As usual, **take care with extractors that /// consume the body stream**, since handlers will no longer be able to read it again without /// putting the body "back" into the request object within your middleware. /// /// ``` /// # use std::collections::HashMap; /// # use actix_web::{ /// # App, Error, /// # body::MessageBody, /// # dev::{ServiceRequest, ServiceResponse}, /// # http::header::{Accept, Date}, /// # web::{Header, Query}, /// # }; /// use actix_web::middleware::Next; /// /// async fn my_extracting_mw( /// accept: Header<Accept>, /// query: Query<HashMap<String, String>>, /// req: ServiceRequest, /// next: Next<impl MessageBody>, /// ) -> Result<ServiceResponse<impl MessageBody>, Error> { /// // pre-processing /// next.call(req).await /// // post-processing /// } /// # App::new().wrap(actix_web::middleware::from_fn(my_extracting_mw)); pub fn from_fn<F, Es>(mw_fn: F) -> MiddlewareFn<F, Es> { MiddlewareFn { mw_fn: Rc::new(mw_fn), _phantom: PhantomData, } } /// Middleware transform for [`from_fn`]. #[allow(missing_debug_implementations)] pub struct MiddlewareFn<F, Es> { mw_fn: Rc<F>, _phantom: PhantomData<Es>, } impl<S, F, Fut, B, B2> Transform<S, ServiceRequest> for MiddlewareFn<F, ()> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, F: Fn(ServiceRequest, Next<B>) -> Fut + 'static, Fut: Future<Output = Result<ServiceResponse<B2>, Error>>, B2: MessageBody, { type Response = ServiceResponse<B2>; type Error = Error; type Transform = MiddlewareFnService<F, B, ()>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(MiddlewareFnService { service: boxed::rc_service(service), mw_fn: Rc::clone(&self.mw_fn), _phantom: PhantomData, })) } } /// Middleware service for [`from_fn`]. #[allow(missing_debug_implementations)] pub struct MiddlewareFnService<F, B, Es> { service: RcService<ServiceRequest, ServiceResponse<B>, Error>, mw_fn: Rc<F>, _phantom: PhantomData<(B, Es)>, } impl<F, Fut, B, B2> Service<ServiceRequest> for MiddlewareFnService<F, B, ()> where F: Fn(ServiceRequest, Next<B>) -> Fut, Fut: Future<Output = Result<ServiceResponse<B2>, Error>>, B2: MessageBody, { type Response = ServiceResponse<B2>; type Error = Error; type Future = Fut; forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { (self.mw_fn)( req, Next::<B> { service: Rc::clone(&self.service), }, ) } } macro_rules! impl_middleware_fn_service { ($($ext_type:ident),*) => { impl<S, F, Fut, B, B2, $($ext_type),*> Transform<S, ServiceRequest> for MiddlewareFn<F, ($($ext_type),*,)> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, F: Fn($($ext_type),*, ServiceRequest, Next<B>) -> Fut + 'static, $($ext_type: FromRequest + 'static,)* Fut: Future<Output = Result<ServiceResponse<B2>, Error>> + 'static, B: MessageBody + 'static, B2: MessageBody + 'static, { type Response = ServiceResponse<B2>; type Error = Error; type Transform = MiddlewareFnService<F, B, ($($ext_type,)*)>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(MiddlewareFnService { service: boxed::rc_service(service), mw_fn: Rc::clone(&self.mw_fn), _phantom: PhantomData, })) } } impl<F, $($ext_type),*, Fut, B: 'static, B2> Service<ServiceRequest> for MiddlewareFnService<F, B, ($($ext_type),*,)> where F: Fn( $($ext_type),*, ServiceRequest, Next<B> ) -> Fut + 'static, $($ext_type: FromRequest + 'static,)* Fut: Future<Output = Result<ServiceResponse<B2>, Error>> + 'static, B2: MessageBody + 'static, { type Response = ServiceResponse<B2>; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; forward_ready!(service); #[allow(nonstandard_style)] fn call(&self, mut req: ServiceRequest) -> Self::Future { let mw_fn = Rc::clone(&self.mw_fn); let service = Rc::clone(&self.service); Box::pin(async move { let ($($ext_type,)*) = req.extract::<($($ext_type,)*)>().await?; (mw_fn)($($ext_type),*, req, Next::<B> { service }).await }) } } }; } impl_middleware_fn_service!(E1); impl_middleware_fn_service!(E1, E2); impl_middleware_fn_service!(E1, E2, E3); impl_middleware_fn_service!(E1, E2, E3, E4); impl_middleware_fn_service!(E1, E2, E3, E4, E5); impl_middleware_fn_service!(E1, E2, E3, E4, E5, E6); impl_middleware_fn_service!(E1, E2, E3, E4, E5, E6, E7); impl_middleware_fn_service!(E1, E2, E3, E4, E5, E6, E7, E8); impl_middleware_fn_service!(E1, E2, E3, E4, E5, E6, E7, E8, E9); /// Wraps the "next" service in the middleware chain. #[allow(missing_debug_implementations)] pub struct Next<B> { service: RcService<ServiceRequest, ServiceResponse<B>, Error>, } impl<B> Next<B> { /// Equivalent to `Service::call(self, req)`. pub fn call(&self, req: ServiceRequest) -> <Self as Service<ServiceRequest>>::Future { Service::call(self, req) } } impl<B> Service<ServiceRequest> for Next<B> { type Response = ServiceResponse<B>; type Error = Error; type Future = BoxFuture<Result<Self::Response, Self::Error>>; forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { self.service.call(req) } } #[cfg(test)] mod tests { use super::*; use crate::{ http::header::{self, HeaderValue}, middleware::{Compat, Logger}, test, web, App, HttpResponse, }; async fn noop<B>(req: ServiceRequest, next: Next<B>) -> Result<ServiceResponse<B>, Error> { next.call(req).await } async fn add_res_header<B>( req: ServiceRequest, next: Next<B>, ) -> Result<ServiceResponse<B>, Error> { let mut res = next.call(req).await?; res.headers_mut() .insert(header::WARNING, HeaderValue::from_static("42")); Ok(res) } async fn mutate_body_type( req: ServiceRequest, next: Next<impl MessageBody + 'static>, ) -> Result<ServiceResponse<impl MessageBody>, Error> { let res = next.call(req).await?; Ok(res.map_into_left_body::<()>()) } struct MyMw(bool); impl MyMw { async fn mw_cb( &self, req: ServiceRequest, next: Next<impl MessageBody + 'static>, ) -> Result<ServiceResponse<impl MessageBody>, Error> { let mut res = match self.0 { true => req.into_response("short-circuited").map_into_right_body(), false => next.call(req).await?.map_into_left_body(), }; res.headers_mut() .insert(header::WARNING, HeaderValue::from_static("42")); Ok(res) } pub fn into_middleware<S, B>( self, ) -> impl Transform< S, ServiceRequest, Response = ServiceResponse<impl MessageBody>, Error = Error, InitError = (), > where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static, B: MessageBody + 'static, { let this = Rc::new(self); from_fn(move |req, next| { let this = Rc::clone(&this); async move { Self::mw_cb(&this, req, next).await } }) } } #[actix_rt::test] async fn compat_compat() { let _ = App::new().wrap(Compat::new(from_fn(noop))); let _ = App::new().wrap(Compat::new(from_fn(mutate_body_type))); } #[actix_rt::test] async fn permits_different_in_and_out_body_types() { let app = test::init_service( App::new() .wrap(from_fn(mutate_body_type)) .wrap(from_fn(add_res_header)) .wrap(Logger::default()) .wrap(from_fn(noop)) .default_service(web::to(HttpResponse::NotFound)), ) .await; let req = test::TestRequest::default().to_request(); let res = test::call_service(&app, req).await; assert!(res.headers().contains_key(header::WARNING)); } #[actix_rt::test] async fn closure_capture_and_return_from_fn() { let app = test::init_service( App::new() .wrap(Logger::default()) .wrap(MyMw(true).into_middleware()) .wrap(Logger::default()), ) .await; let req = test::TestRequest::default().to_request(); let res = test::call_service(&app, req).await; assert!(res.headers().contains_key(header::WARNING)); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/mod.rs
actix-web/src/middleware/mod.rs
//! A collection of common middleware. //! //! # What Is Middleware? //! //! Actix Web's middleware system allows us to add additional behavior to request/response //! processing. Middleware can hook into incoming request and outgoing response processes, enabling //! us to modify requests and responses as well as halt request processing to return a response //! early. //! //! Typically, middleware is involved in the following actions: //! //! - Pre-process the request (e.g., [normalizing paths](NormalizePath)) //! - Post-process a response (e.g., [logging][Logger]) //! - Modify application state (through [`ServiceRequest`][crate::dev::ServiceRequest]) //! - Access external services (e.g., [sessions](https://docs.rs/actix-session), etc.) //! //! Middleware is registered for each [`App`], [`Scope`](crate::Scope), or //! [`Resource`](crate::Resource) and executed in opposite order as registration. //! //! # Simple Middleware //! //! In many cases, you can model your middleware as an async function via the [`from_fn()`] helper //! that provides a natural interface for implementing your desired behaviors. //! //! ``` //! # use actix_web::{ //! # App, Error, //! # body::MessageBody, //! # dev::{ServiceRequest, ServiceResponse, Service as _}, //! # }; //! use actix_web::middleware::{self, Next}; //! //! async fn my_mw( //! req: ServiceRequest, //! next: Next<impl MessageBody>, //! ) -> Result<ServiceResponse<impl MessageBody>, Error> { //! // pre-processing //! //! // invoke the wrapped middleware or service //! let res = next.call(req).await?; //! //! // post-processing //! //! Ok(res) //! } //! //! App::new() //! .wrap(middleware::from_fn(my_mw)); //! ``` //! //! ## Complex Middleware //! //! In the more general ase, a middleware is a pair of types that implements the [`Service`] trait //! and [`Transform`] trait, respectively. The [`new_transform`] and [`call`] methods must return a //! [`Future`], though it can often be [an immediately-ready one](actix_utils::future::Ready). //! //! All the built-in middleware use this pattern with pairs of builder (`Transform`) + //! implementation (`Service`) types. //! //! # Ordering //! //! ``` //! # use actix_web::{web, middleware, get, App, Responder}; //! # //! # // some basic types to make sure this compiles //! # type ExtractorA = web::Json<String>; //! # type ExtractorB = ExtractorA; //! #[get("/")] //! async fn service(a: ExtractorA, b: ExtractorB) -> impl Responder { "Hello, World!" } //! //! # fn main() { //! # // These aren't snake_case, because they are supposed to be unit structs. //! # type MiddlewareA = middleware::Compress; //! # type MiddlewareB = middleware::Compress; //! # type MiddlewareC = middleware::Compress; //! let app = App::new() //! .wrap(MiddlewareA::default()) //! .wrap(MiddlewareB::default()) //! .wrap(MiddlewareC::default()) //! .service(service); //! # } //! ``` //! //! ```plain //! Request //! ⭣ //! ╭────────────────────┼────╮ //! │ MiddlewareC │ │ //! │ ╭──────────────────┼───╮│ //! │ │ MiddlewareB │ ││ //! │ │ ╭────────────────┼──╮││ //! │ │ │ MiddlewareA │ │││ //! │ │ │ ╭──────────────┼─╮│││ //! │ │ │ │ ExtractorA │ ││││ //! │ │ │ ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┼┈┤│││ //! │ │ │ │ ExtractorB │ ││││ //! │ │ │ ├┈┈┈┈┈┈┈┈┈┈┈┈┈┈┼┈┤│││ //! │ │ │ │ service │ ││││ //! │ │ │ ╰──────────────┼─╯│││ //! │ │ ╰────────────────┼──╯││ //! │ ╰──────────────────┼───╯│ //! ╰────────────────────┼────╯ //! ⭣ //! Response //! ``` //! The request _first_ gets processed by the middleware specified _last_ - `MiddlewareC`. It passes //! the request (possibly a modified one) to the next middleware - `MiddlewareB` - _or_ directly //! responds to the request (e.g. when the request was invalid or an error occurred). `MiddlewareB` //! processes the request as well and passes it to `MiddlewareA`, which then passes it to the //! [`Service`]. In the [`Service`], the extractors will run first. They don't pass the request on, //! but only view it (see [`FromRequest`]). After the [`Service`] responds to the request, the //! response is passed back through `MiddlewareA`, `MiddlewareB`, and `MiddlewareC`. //! //! As you register middleware using [`wrap`][crate::App::wrap] and [`wrap_fn`][crate::App::wrap_fn] //! in the [`App`] builder, imagine wrapping layers around an inner [`App`]. The first middleware //! layer exposed to a Request is the outermost layer (i.e., the _last_ registered in the builder //! chain, in the example above: `MiddlewareC`). Consequently, the _first_ middleware registered in //! the builder chain is the _last_ to start executing during request processing (`MiddlewareA`). //! Ordering is less obvious when wrapped services also have middleware applied. In this case, //! middleware are run in reverse order for [`App`] _and then_ in reverse order for the wrapped //! service. //! //! # Middleware Traits //! //! ## `Transform<S, Req>` //! //! The [`Transform`] trait is the builder for the actual [`Service`]s that handle the requests. All //! the middleware you pass to the `wrap` methods implement this trait. During construction, each //! thread assembles a chain of [`Service`]s by calling [`new_transform`] and passing the next //! [`Service`] (`S`) in the chain. The created [`Service`] handles requests of type `Req`. //! //! In the example from the [ordering](#ordering) section, the chain would be: //! //! ```plain //! MiddlewareCService { //! next: MiddlewareBService { //! next: MiddlewareAService { ... } //! } //! } //! ``` //! //! ## `Service<Req>` //! //! A [`Service`] `S` represents an asynchronous operation that turns a request of type `Req` into a //! response of type [`S::Response`](crate::dev::Service::Response) or an error of type //! [`S::Error`](crate::dev::Service::Error). You can think of the service of being roughly: //! //! ```ignore //! async fn(&self, req: Req) -> Result<S::Response, S::Error> //! ``` //! //! In most cases the [`Service`] implementation will, at some point, call the wrapped [`Service`] //! in its [`call`] implementation. //! //! Note that the [`Service`]s created by [`new_transform`] don't need to be [`Send`] or [`Sync`]. //! //! # Example //! //! ``` //! use std::{future::{ready, Ready, Future}, pin::Pin}; //! //! use actix_web::{ //! dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform}, //! web, Error, //! # App //! }; //! //! pub struct SayHi; //! //! // `S` - type of the next service //! // `B` - type of response's body //! impl<S, B> Transform<S, ServiceRequest> for SayHi //! where //! S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, //! S::Future: 'static, //! B: 'static, //! { //! type Response = ServiceResponse<B>; //! type Error = Error; //! type InitError = (); //! type Transform = SayHiMiddleware<S>; //! type Future = Ready<Result<Self::Transform, Self::InitError>>; //! //! fn new_transform(&self, service: S) -> Self::Future { //! ready(Ok(SayHiMiddleware { service })) //! } //! } //! //! pub struct SayHiMiddleware<S> { //! /// The next service to call //! service: S, //! } //! //! // This future doesn't have the requirement of being `Send`. //! // See: futures_util::future::LocalBoxFuture //! type LocalBoxFuture<T> = Pin<Box<dyn Future<Output = T> + 'static>>; //! //! // `S`: type of the wrapped service //! // `B`: type of the body - try to be generic over the body where possible //! impl<S, B> Service<ServiceRequest> for SayHiMiddleware<S> //! where //! S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, //! S::Future: 'static, //! B: 'static, //! { //! type Response = ServiceResponse<B>; //! type Error = Error; //! type Future = LocalBoxFuture<Result<Self::Response, Self::Error>>; //! //! // This service is ready when its next service is ready //! forward_ready!(service); //! //! fn call(&self, req: ServiceRequest) -> Self::Future { //! println!("Hi from start. You requested: {}", req.path()); //! //! // A more complex middleware, could return an error or an early response here. //! //! let fut = self.service.call(req); //! //! Box::pin(async move { //! let res = fut.await?; //! //! println!("Hi from response"); //! Ok(res) //! }) //! } //! } //! //! # fn main() { //! let app = App::new() //! .wrap(SayHi) //! .route("/", web::get().to(|| async { "Hello, middleware!" })); //! # } //! ``` //! //! [`Future`]: std::future::Future //! [`App`]: crate::App //! [`FromRequest`]: crate::FromRequest //! [`Service`]: crate::dev::Service //! [`Transform`]: crate::dev::Transform //! [`call`]: crate::dev::Service::call() //! [`new_transform`]: crate::dev::Transform::new_transform() //! [`from_fn`]: crate mod compat; #[cfg(feature = "__compress")] mod compress; mod condition; mod default_headers; mod err_handlers; mod from_fn; mod identity; mod logger; mod normalize; #[cfg(feature = "__compress")] pub use self::compress::Compress; pub use self::{ compat::Compat, condition::Condition, default_headers::DefaultHeaders, err_handlers::{ErrorHandlerResponse, ErrorHandlers}, from_fn::{from_fn, Next}, identity::Identity, logger::Logger, normalize::{NormalizePath, TrailingSlash}, }; #[cfg(test)] mod tests { use super::*; use crate::{http::StatusCode, App}; #[test] fn common_combinations() { // ensure there's no reason that the built-in middleware cannot compose let _ = App::new() .wrap(Compat::new(Logger::default())) .wrap(Condition::new(true, DefaultHeaders::new())) .wrap(DefaultHeaders::new().add(("X-Test2", "X-Value2"))) .wrap(ErrorHandlers::new().handler(StatusCode::FORBIDDEN, |res| { Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) })) .wrap(Logger::default()) .wrap(NormalizePath::new(TrailingSlash::Trim)); let _ = App::new() .wrap(NormalizePath::new(TrailingSlash::Trim)) .wrap(Logger::default()) .wrap(ErrorHandlers::new().handler(StatusCode::FORBIDDEN, |res| { Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) })) .wrap(DefaultHeaders::new().add(("X-Test2", "X-Value2"))) .wrap(Condition::new(true, DefaultHeaders::new())) .wrap(Compat::new(Logger::default())); #[cfg(feature = "__compress")] { let _ = App::new().wrap(Compress::default()).wrap(Logger::default()); let _ = App::new().wrap(Logger::default()).wrap(Compress::default()); let _ = App::new().wrap(Compat::new(Compress::default())); let _ = App::new().wrap(Condition::new(true, Compat::new(Compress::default()))); } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/condition.rs
actix-web/src/middleware/condition.rs
//! For middleware documentation, see [`Condition`]. use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use futures_core::{future::LocalBoxFuture, ready}; use futures_util::FutureExt as _; use pin_project_lite::pin_project; use crate::{ body::EitherBody, dev::{Service, ServiceResponse, Transform}, }; /// Middleware for conditionally enabling other middleware. /// /// # Examples /// ``` /// use actix_web::middleware::{Condition, NormalizePath}; /// use actix_web::App; /// /// let enable_normalize = std::env::var("NORMALIZE_PATH").is_ok(); /// let app = App::new() /// .wrap(Condition::new(enable_normalize, NormalizePath::default())); /// ``` pub struct Condition<T> { transformer: T, enable: bool, } impl<T> Condition<T> { pub fn new(enable: bool, transformer: T) -> Self { Self { transformer, enable, } } } impl<S, T, Req, BE, BD, Err> Transform<S, Req> for Condition<T> where S: Service<Req, Response = ServiceResponse<BD>, Error = Err> + 'static, T: Transform<S, Req, Response = ServiceResponse<BE>, Error = Err>, T::Future: 'static, T::InitError: 'static, T::Transform: 'static, { type Response = ServiceResponse<EitherBody<BE, BD>>; type Error = Err; type Transform = ConditionMiddleware<T::Transform, S>; type InitError = T::InitError; type Future = LocalBoxFuture<'static, Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { if self.enable { let fut = self.transformer.new_transform(service); async move { let wrapped_svc = fut.await?; Ok(ConditionMiddleware::Enable(wrapped_svc)) } .boxed_local() } else { async move { Ok(ConditionMiddleware::Disable(service)) }.boxed_local() } } } pub enum ConditionMiddleware<E, D> { Enable(E), Disable(D), } impl<E, D, Req, BE, BD, Err> Service<Req> for ConditionMiddleware<E, D> where E: Service<Req, Response = ServiceResponse<BE>, Error = Err>, D: Service<Req, Response = ServiceResponse<BD>, Error = Err>, { type Response = ServiceResponse<EitherBody<BE, BD>>; type Error = Err; type Future = ConditionMiddlewareFuture<E::Future, D::Future>; fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { match self { ConditionMiddleware::Enable(service) => service.poll_ready(cx), ConditionMiddleware::Disable(service) => service.poll_ready(cx), } } fn call(&self, req: Req) -> Self::Future { match self { ConditionMiddleware::Enable(service) => ConditionMiddlewareFuture::Enabled { fut: service.call(req), }, ConditionMiddleware::Disable(service) => ConditionMiddlewareFuture::Disabled { fut: service.call(req), }, } } } pin_project! { #[doc(hidden)] #[project = ConditionProj] pub enum ConditionMiddlewareFuture<E, D> { Enabled { #[pin] fut: E, }, Disabled { #[pin] fut: D, }, } } impl<E, D, BE, BD, Err> Future for ConditionMiddlewareFuture<E, D> where E: Future<Output = Result<ServiceResponse<BE>, Err>>, D: Future<Output = Result<ServiceResponse<BD>, Err>>, { type Output = Result<ServiceResponse<EitherBody<BE, BD>>, Err>; #[inline] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let res = match self.project() { ConditionProj::Enabled { fut } => ready!(fut.poll(cx))?.map_into_left_body(), ConditionProj::Disabled { fut } => ready!(fut.poll(cx))?.map_into_right_body(), }; Poll::Ready(Ok(res)) } } #[cfg(test)] mod tests { use actix_service::IntoService as _; use super::*; use crate::{ body::BoxBody, dev::ServiceRequest, error::Result, http::{ header::{HeaderValue, CONTENT_TYPE}, StatusCode, }, middleware::{self, ErrorHandlerResponse, ErrorHandlers, Identity}, test::{self, TestRequest}, web::Bytes, HttpResponse, }; #[allow(clippy::unnecessary_wraps)] fn render_500<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) } #[test] fn compat_with_builtin_middleware() { let _ = Condition::new(true, middleware::Compat::new(Identity)); let _ = Condition::new(true, middleware::Logger::default()); let _ = Condition::new(true, middleware::Compress::default()); let _ = Condition::new(true, middleware::NormalizePath::trim()); let _ = Condition::new(true, middleware::DefaultHeaders::new()); let _ = Condition::new(true, middleware::ErrorHandlers::<BoxBody>::new()); let _ = Condition::new(true, middleware::ErrorHandlers::<Bytes>::new()); } #[actix_rt::test] async fn test_handler_enabled() { let srv = |req: ServiceRequest| async move { let resp = HttpResponse::InternalServerError().message_body(String::new())?; Ok(req.into_response(resp)) }; let mw = ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, render_500); let mw = Condition::new(true, mw) .new_transform(srv.into_service()) .await .unwrap(); let resp: ServiceResponse<EitherBody<EitherBody<_, _>, String>> = test::call_service(&mw, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); } #[actix_rt::test] async fn test_handler_disabled() { let srv = |req: ServiceRequest| async move { let resp = HttpResponse::InternalServerError().message_body(String::new())?; Ok(req.into_response(resp)) }; let mw = ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, render_500); let mw = Condition::new(false, mw) .new_transform(srv.into_service()) .await .unwrap(); let resp: ServiceResponse<EitherBody<EitherBody<_, _>, String>> = test::call_service(&mw, TestRequest::default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE), None); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/normalize.rs
actix-web/src/middleware/normalize.rs
//! For middleware documentation, see [`NormalizePath`]. use actix_http::uri::{PathAndQuery, Uri}; use actix_service::{Service, Transform}; use actix_utils::future::{ready, Ready}; use bytes::Bytes; #[cfg(feature = "unicode")] use regex::Regex; #[cfg(not(feature = "unicode"))] use regex_lite::Regex; use crate::{ service::{ServiceRequest, ServiceResponse}, Error, }; /// Determines the behavior of the [`NormalizePath`] middleware. /// /// The default is `TrailingSlash::Trim`. #[non_exhaustive] #[derive(Debug, Clone, Copy, Default)] pub enum TrailingSlash { /// Trim trailing slashes from the end of the path. /// /// Using this will require all routes to omit trailing slashes for them to be accessible. #[default] Trim, /// Only merge any present multiple trailing slashes. /// /// This option provides the best compatibility with behavior in actix-web v2.0. MergeOnly, /// Always add a trailing slash to the end of the path. /// /// Using this will require all routes have a trailing slash for them to be accessible. Always, } /// Middleware for normalizing a request's path so that routes can be matched more flexibly. /// /// # Normalization Steps /// - Merges consecutive slashes into one. (For example, `/path//one` always becomes `/path/one`.) /// - Appends a trailing slash if one is not present, removes one if present, or keeps trailing /// slashes as-is, depending on which [`TrailingSlash`] variant is supplied /// to [`new`](NormalizePath::new()). /// /// # Default Behavior /// The default constructor chooses to strip trailing slashes from the end of paths with them /// ([`TrailingSlash::Trim`]). The implication is that route definitions should be defined without /// trailing slashes or else they will be inaccessible (or vice versa when using the /// `TrailingSlash::Always` behavior), as shown in the example tests below. /// /// # Examples /// ``` /// use actix_web::{web, middleware, App}; /// /// # actix_web::rt::System::new().block_on(async { /// let app = App::new() /// .wrap(middleware::NormalizePath::trim()) /// .route("/test", web::get().to(|| async { "test" })) /// .route("/unmatchable/", web::get().to(|| async { "unmatchable" })); /// /// use actix_web::http::StatusCode; /// use actix_web::test::{call_service, init_service, TestRequest}; /// /// let app = init_service(app).await; /// /// let req = TestRequest::with_uri("/test").to_request(); /// let res = call_service(&app, req).await; /// assert_eq!(res.status(), StatusCode::OK); /// /// let req = TestRequest::with_uri("/test/").to_request(); /// let res = call_service(&app, req).await; /// assert_eq!(res.status(), StatusCode::OK); /// /// let req = TestRequest::with_uri("/unmatchable").to_request(); /// let res = call_service(&app, req).await; /// assert_eq!(res.status(), StatusCode::NOT_FOUND); /// /// let req = TestRequest::with_uri("/unmatchable/").to_request(); /// let res = call_service(&app, req).await; /// assert_eq!(res.status(), StatusCode::NOT_FOUND); /// # }) /// ``` #[derive(Debug, Clone, Copy)] pub struct NormalizePath(TrailingSlash); impl Default for NormalizePath { fn default() -> Self { log::warn!( "`NormalizePath::default()` is deprecated. The default trailing slash behavior changed \ in v4 from `Always` to `Trim`. Update your call to `NormalizePath::new(...)`." ); Self(TrailingSlash::Trim) } } impl NormalizePath { /// Create new `NormalizePath` middleware with the specified trailing slash style. pub fn new(trailing_slash_style: TrailingSlash) -> Self { Self(trailing_slash_style) } /// Constructs a new `NormalizePath` middleware with [trim](TrailingSlash::Trim) semantics. /// /// Use this instead of `NormalizePath::default()` to avoid deprecation warning. pub fn trim() -> Self { Self::new(TrailingSlash::Trim) } } impl<S, B> Transform<S, ServiceRequest> for NormalizePath where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Transform = NormalizePathNormalization<S>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(NormalizePathNormalization { service, merge_slash: Regex::new("//+").unwrap(), trailing_slash_behavior: self.0, })) } } pub struct NormalizePathNormalization<S> { service: S, merge_slash: Regex, trailing_slash_behavior: TrailingSlash, } impl<S, B> Service<ServiceRequest> for NormalizePathNormalization<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Future = S::Future; actix_service::forward_ready!(service); fn call(&self, mut req: ServiceRequest) -> Self::Future { let head = req.head_mut(); let original_path = head.uri.path(); // An empty path here means that the URI has no valid path. We skip normalization in this // case, because adding a path can make the URI invalid if !original_path.is_empty() { // Either adds a string to the end (duplicates will be removed anyways) or trims all // slashes from the end let path = match self.trailing_slash_behavior { TrailingSlash::Always => format!("{}/", original_path), TrailingSlash::MergeOnly => original_path.to_string(), TrailingSlash::Trim => original_path.trim_end_matches('/').to_string(), }; // normalize multiple /'s to one / let path = self.merge_slash.replace_all(&path, "/"); // Ensure root paths are still resolvable. If resulting path is blank after previous // step it means the path was one or more slashes. Reduce to single slash. let path = if path.is_empty() { "/" } else { path.as_ref() }; // Check whether the path has been changed // // This check was previously implemented as string length comparison // // That approach fails when a trailing slash is added, // and a duplicate slash is removed, // since the length of the strings remains the same // // For example, the path "/v1//s" will be normalized to "/v1/s/" // Both of the paths have the same length, // so the change can not be deduced from the length comparison if path != original_path { let mut parts = head.uri.clone().into_parts(); let query = parts.path_and_query.as_ref().and_then(|pq| pq.query()); let path = match query { Some(q) => Bytes::from(format!("{}?{}", path, q)), None => Bytes::copy_from_slice(path.as_bytes()), }; parts.path_and_query = Some(PathAndQuery::from_maybe_shared(path).unwrap()); let uri = Uri::from_parts(parts).unwrap(); req.match_info_mut().get_mut().update(&uri); req.head_mut().uri = uri; } } self.service.call(req) } } #[cfg(test)] mod tests { use actix_http::StatusCode; use actix_service::IntoService; use super::*; use crate::{ guard::fn_guard, test::{call_service, init_service, TestRequest}, web, App, HttpResponse, }; #[actix_rt::test] async fn test_wrap() { let app = init_service( App::new() .wrap(NormalizePath::default()) .service(web::resource("/").to(HttpResponse::Ok)) .service(web::resource("/v1/something").to(HttpResponse::Ok)) .service( web::resource("/v2/something") .guard(fn_guard(|ctx| ctx.head().uri.query() == Some("query=test"))) .to(HttpResponse::Ok), ), ) .await; let test_uris = vec![ "/", "/?query=test", "///", "/v1//something", "/v1//something////", "//v1/something", "//v1//////something", "/v2//something?query=test", "/v2//something////?query=test", "//v2/something?query=test", "//v2//////something?query=test", ]; for uri in test_uris { let req = TestRequest::with_uri(uri).to_request(); let res = call_service(&app, req).await; assert!(res.status().is_success(), "Failed uri: {}", uri); } } #[actix_rt::test] async fn trim_trailing_slashes() { let app = init_service( App::new() .wrap(NormalizePath(TrailingSlash::Trim)) .service(web::resource("/").to(HttpResponse::Ok)) .service(web::resource("/v1/something").to(HttpResponse::Ok)) .service( web::resource("/v2/something") .guard(fn_guard(|ctx| ctx.head().uri.query() == Some("query=test"))) .to(HttpResponse::Ok), ), ) .await; let test_uris = vec![ "/", "///", "/v1/something", "/v1/something/", "/v1/something////", "//v1//something", "//v1//something//", "/v2/something?query=test", "/v2/something/?query=test", "/v2/something////?query=test", "//v2//something?query=test", "//v2//something//?query=test", ]; for uri in test_uris { let req = TestRequest::with_uri(uri).to_request(); let res = call_service(&app, req).await; assert!(res.status().is_success(), "Failed uri: {}", uri); } } #[actix_rt::test] async fn trim_root_trailing_slashes_with_query() { let app = init_service( App::new().wrap(NormalizePath(TrailingSlash::Trim)).service( web::resource("/") .guard(fn_guard(|ctx| ctx.head().uri.query() == Some("query=test"))) .to(HttpResponse::Ok), ), ) .await; let test_uris = vec!["/?query=test", "//?query=test", "///?query=test"]; for uri in test_uris { let req = TestRequest::with_uri(uri).to_request(); let res = call_service(&app, req).await; assert!(res.status().is_success(), "Failed uri: {}", uri); } } #[actix_rt::test] async fn ensure_trailing_slash() { let app = init_service( App::new() .wrap(NormalizePath(TrailingSlash::Always)) .service(web::resource("/").to(HttpResponse::Ok)) .service(web::resource("/v1/something/").to(HttpResponse::Ok)) .service( web::resource("/v2/something/") .guard(fn_guard(|ctx| ctx.head().uri.query() == Some("query=test"))) .to(HttpResponse::Ok), ), ) .await; let test_uris = vec![ "/", "///", "/v1/something", "/v1/something/", "/v1/something////", "//v1//something", "//v1//something//", "/v2/something?query=test", "/v2/something/?query=test", "/v2/something////?query=test", "//v2//something?query=test", "//v2//something//?query=test", ]; for uri in test_uris { let req = TestRequest::with_uri(uri).to_request(); let res = call_service(&app, req).await; assert!(res.status().is_success(), "Failed uri: {}", uri); } } #[actix_rt::test] async fn ensure_root_trailing_slash_with_query() { let app = init_service( App::new() .wrap(NormalizePath(TrailingSlash::Always)) .service( web::resource("/") .guard(fn_guard(|ctx| ctx.head().uri.query() == Some("query=test"))) .to(HttpResponse::Ok), ), ) .await; let test_uris = vec!["/?query=test", "//?query=test", "///?query=test"]; for uri in test_uris { let req = TestRequest::with_uri(uri).to_request(); let res = call_service(&app, req).await; assert!(res.status().is_success(), "Failed uri: {}", uri); } } #[actix_rt::test] async fn keep_trailing_slash_unchanged() { let app = init_service( App::new() .wrap(NormalizePath(TrailingSlash::MergeOnly)) .service(web::resource("/").to(HttpResponse::Ok)) .service(web::resource("/v1/something").to(HttpResponse::Ok)) .service(web::resource("/v1/").to(HttpResponse::Ok)) .service( web::resource("/v2/something") .guard(fn_guard(|ctx| ctx.head().uri.query() == Some("query=test"))) .to(HttpResponse::Ok), ), ) .await; let tests = vec![ ("/", true), // root paths should still work ("/?query=test", true), ("///", true), ("/v1/something////", false), ("/v1/something/", false), ("//v1//something", true), ("/v1/", true), ("/v1", false), ("/v1////", true), ("//v1//", true), ("///v1", false), ("/v2/something?query=test", true), ("/v2/something/?query=test", false), ("/v2/something//?query=test", false), ("//v2//something?query=test", true), ]; for (uri, success) in tests { let req = TestRequest::with_uri(uri).to_request(); let res = call_service(&app, req).await; assert_eq!(res.status().is_success(), success, "Failed uri: {}", uri); } } #[actix_rt::test] async fn no_path() { let app = init_service( App::new() .wrap(NormalizePath::default()) .service(web::resource("/").to(HttpResponse::Ok)), ) .await; // This URI will be interpreted as an authority form, i.e. there is no path nor scheme // (https://datatracker.ietf.org/doc/html/rfc7230#section-5.3.3) let req = TestRequest::with_uri("eh").to_request(); let res = call_service(&app, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_in_place_normalization() { let srv = |req: ServiceRequest| { assert_eq!("/v1/something", req.path()); ready(Ok(req.into_response(HttpResponse::Ok().finish()))) }; let normalize = NormalizePath::default() .new_transform(srv.into_service()) .await .unwrap(); let test_uris = vec![ "/v1//something////", "///v1/something", "//v1///something", "/v1//something", ]; for uri in test_uris { let req = TestRequest::with_uri(uri).to_srv_request(); let res = normalize.call(req).await.unwrap(); assert!(res.status().is_success(), "Failed uri: {}", uri); } } #[actix_rt::test] async fn should_normalize_nothing() { const URI: &str = "/v1/something"; let srv = |req: ServiceRequest| { assert_eq!(URI, req.path()); ready(Ok(req.into_response(HttpResponse::Ok().finish()))) }; let normalize = NormalizePath::default() .new_transform(srv.into_service()) .await .unwrap(); let req = TestRequest::with_uri(URI).to_srv_request(); let res = normalize.call(req).await.unwrap(); assert!(res.status().is_success()); } #[actix_rt::test] async fn should_normalize_no_trail() { let srv = |req: ServiceRequest| { assert_eq!("/v1/something", req.path()); ready(Ok(req.into_response(HttpResponse::Ok().finish()))) }; let normalize = NormalizePath::default() .new_transform(srv.into_service()) .await .unwrap(); let req = TestRequest::with_uri("/v1/something/").to_srv_request(); let res = normalize.call(req).await.unwrap(); assert!(res.status().is_success()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/identity.rs
actix-web/src/middleware/identity.rs
//! A no-op middleware. See [Noop] for docs. use actix_utils::future::{ready, Ready}; use crate::dev::{forward_ready, Service, Transform}; /// A no-op middleware that passes through request and response untouched. #[derive(Debug, Clone, Default)] #[non_exhaustive] pub struct Identity; impl<S: Service<Req>, Req> Transform<S, Req> for Identity { type Response = S::Response; type Error = S::Error; type Transform = IdentityMiddleware<S>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; #[inline] fn new_transform(&self, service: S) -> Self::Future { ready(Ok(IdentityMiddleware { service })) } } #[doc(hidden)] pub struct IdentityMiddleware<S> { service: S, } impl<S: Service<Req>, Req> Service<Req> for IdentityMiddleware<S> { type Response = S::Response; type Error = S::Error; type Future = S::Future; forward_ready!(service); #[inline] fn call(&self, req: Req) -> Self::Future { self.service.call(req) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/default_headers.rs
actix-web/src/middleware/default_headers.rs
//! For middleware documentation, see [`DefaultHeaders`]. use std::{ future::Future, marker::PhantomData, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_http::error::HttpError; use actix_utils::future::{ready, Ready}; use futures_core::ready; use pin_project_lite::pin_project; use crate::{ dev::{Service, Transform}, http::header::{HeaderMap, HeaderName, HeaderValue, TryIntoHeaderPair, CONTENT_TYPE}, service::{ServiceRequest, ServiceResponse}, Error, }; /// Middleware for setting default response headers. /// /// Headers with the same key that are already set in a response will *not* be overwritten. /// /// # Examples /// ``` /// use actix_web::{web, http, middleware, App, HttpResponse}; /// /// let app = App::new() /// .wrap(middleware::DefaultHeaders::new().add(("X-Version", "0.2"))) /// .service( /// web::resource("/test") /// .route(web::get().to(|| HttpResponse::Ok())) /// .route(web::method(http::Method::HEAD).to(|| HttpResponse::MethodNotAllowed())) /// ); /// ``` #[derive(Debug, Clone, Default)] pub struct DefaultHeaders { inner: Rc<Inner>, } #[derive(Debug, Default)] struct Inner { headers: HeaderMap, } impl DefaultHeaders { /// Constructs an empty `DefaultHeaders` middleware. #[inline] pub fn new() -> DefaultHeaders { DefaultHeaders::default() } /// Adds a header to the default set. /// /// # Panics /// Panics when resolved header name or value is invalid. #[allow(clippy::should_implement_trait)] pub fn add(mut self, header: impl TryIntoHeaderPair) -> Self { // standard header terminology `insert` or `append` for this method would make the behavior // of this middleware less obvious since it only adds the headers if they are not present match header.try_into_pair() { Ok((key, value)) => Rc::get_mut(&mut self.inner) .expect("All default headers must be added before cloning.") .headers .append(key, value), Err(err) => panic!("Invalid header: {}", err.into()), } self } #[doc(hidden)] #[deprecated( since = "4.0.0", note = "Prefer `.add((key, value))`. Will be removed in v5." )] pub fn header<K, V>(self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<HttpError>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<HttpError>, { self.add(( HeaderName::try_from(key) .map_err(Into::into) .expect("Invalid header name"), HeaderValue::try_from(value) .map_err(Into::into) .expect("Invalid header value"), )) } /// Adds a default *Content-Type* header if response does not contain one. /// /// Default is `application/octet-stream`. pub fn add_content_type(self) -> Self { #[allow(clippy::declare_interior_mutable_const)] const HV_MIME: HeaderValue = HeaderValue::from_static("application/octet-stream"); self.add((CONTENT_TYPE, HV_MIME)) } } impl<S, B> Transform<S, ServiceRequest> for DefaultHeaders where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Transform = DefaultHeadersMiddleware<S>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(DefaultHeadersMiddleware { service, inner: Rc::clone(&self.inner), })) } } pub struct DefaultHeadersMiddleware<S> { service: S, inner: Rc<Inner>, } impl<S, B> Service<ServiceRequest> for DefaultHeadersMiddleware<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Future = DefaultHeaderFuture<S, B>; actix_service::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { let inner = Rc::clone(&self.inner); let fut = self.service.call(req); DefaultHeaderFuture { fut, inner, _body: PhantomData, } } } pin_project! { pub struct DefaultHeaderFuture<S: Service<ServiceRequest>, B> { #[pin] fut: S::Future, inner: Rc<Inner>, _body: PhantomData<B>, } } impl<S, B> Future for DefaultHeaderFuture<S, B> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, { type Output = <S::Future as Future>::Output; #[allow(clippy::borrow_interior_mutable_const)] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.project(); let mut res = ready!(this.fut.poll(cx))?; // set response headers for (key, value) in this.inner.headers.iter() { if !res.headers().contains_key(key) { res.headers_mut().insert(key.clone(), value.clone()); } } Poll::Ready(Ok(res)) } } #[cfg(test)] mod tests { use actix_service::IntoService; use actix_utils::future::ok; use super::*; use crate::{ test::{self, TestRequest}, HttpResponse, }; #[actix_rt::test] async fn adding_default_headers() { let mw = DefaultHeaders::new() .add(("X-TEST", "0001")) .add(("X-TEST-TWO", HeaderValue::from_static("123"))) .new_transform(test::ok_service()) .await .unwrap(); let req = TestRequest::default().to_srv_request(); let res = mw.call(req).await.unwrap(); assert_eq!(res.headers().get("x-test").unwrap(), "0001"); assert_eq!(res.headers().get("x-test-two").unwrap(), "123"); } #[actix_rt::test] async fn no_override_existing() { let req = TestRequest::default().to_srv_request(); let srv = |req: ServiceRequest| { ok(req.into_response( HttpResponse::Ok() .insert_header((CONTENT_TYPE, "0002")) .finish(), )) }; let mw = DefaultHeaders::new() .add((CONTENT_TYPE, "0001")) .new_transform(srv.into_service()) .await .unwrap(); let resp = mw.call(req).await.unwrap(); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0002"); } #[actix_rt::test] async fn adding_content_type() { let mw = DefaultHeaders::new() .add_content_type() .new_transform(test::ok_service()) .await .unwrap(); let req = TestRequest::default().to_srv_request(); let resp = mw.call(req).await.unwrap(); assert_eq!( resp.headers().get(CONTENT_TYPE).unwrap(), "application/octet-stream" ); } #[test] #[should_panic] fn invalid_header_name() { DefaultHeaders::new().add((":", "hello")); } #[test] #[should_panic] fn invalid_header_value() { DefaultHeaders::new().add(("x-test", "\n")); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/middleware/compat.rs
actix-web/src/middleware/compat.rs
//! For middleware documentation, see [`Compat`]. use std::{ future::Future, pin::Pin, task::{Context, Poll}, }; use futures_core::{future::LocalBoxFuture, ready}; use pin_project_lite::pin_project; use crate::{ body::{BoxBody, MessageBody}, dev::{Service, Transform}, error::Error, service::ServiceResponse, }; /// Middleware for enabling any middleware to be used in [`Resource::wrap`](crate::Resource::wrap), /// and [`Condition`](super::Condition). /// /// # Examples /// ``` /// use actix_web::middleware::{Logger, Compat}; /// use actix_web::{App, web}; /// /// let logger = Logger::default(); /// /// // this would not compile because of incompatible body types /// // let app = App::new() /// // .service(web::scope("scoped").wrap(logger)); /// /// // by using this middleware we can use the logger on a scope /// let app = App::new() /// .service(web::scope("scoped").wrap(Compat::new(logger))); /// ``` pub struct Compat<T> { transform: T, } impl<T> Compat<T> { /// Wrap a middleware to give it broader compatibility. pub fn new(middleware: T) -> Self { Self { transform: middleware, } } } impl<S, T, Req> Transform<S, Req> for Compat<T> where S: Service<Req>, T: Transform<S, Req>, T::Future: 'static, T::Response: MapServiceResponseBody, T::Error: Into<Error>, { type Response = ServiceResponse<BoxBody>; type Error = Error; type Transform = CompatMiddleware<T::Transform>; type InitError = T::InitError; type Future = LocalBoxFuture<'static, Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { let fut = self.transform.new_transform(service); Box::pin(async move { let service = fut.await?; Ok(CompatMiddleware { service }) }) } } pub struct CompatMiddleware<S> { service: S, } impl<S, Req> Service<Req> for CompatMiddleware<S> where S: Service<Req>, S::Response: MapServiceResponseBody, S::Error: Into<Error>, { type Response = ServiceResponse<BoxBody>; type Error = Error; type Future = CompatMiddlewareFuture<S::Future>; actix_service::forward_ready!(service); fn call(&self, req: Req) -> Self::Future { let fut = self.service.call(req); CompatMiddlewareFuture { fut } } } pin_project! { pub struct CompatMiddlewareFuture<Fut> { #[pin] fut: Fut, } } impl<Fut, T, E> Future for CompatMiddlewareFuture<Fut> where Fut: Future<Output = Result<T, E>>, T: MapServiceResponseBody, E: Into<Error>, { type Output = Result<ServiceResponse<BoxBody>, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let res = match ready!(self.project().fut.poll(cx)) { Ok(res) => res, Err(err) => return Poll::Ready(Err(err.into())), }; Poll::Ready(Ok(res.map_body())) } } /// Convert `ServiceResponse`'s `ResponseBody<B>` generic type to `ResponseBody<Body>`. pub trait MapServiceResponseBody { fn map_body(self) -> ServiceResponse<BoxBody>; } impl<B> MapServiceResponseBody for ServiceResponse<B> where B: MessageBody + 'static, { #[inline] fn map_body(self) -> ServiceResponse<BoxBody> { self.map_into_boxed_body() } } #[cfg(test)] mod tests { // easier to code when cookies feature is disabled #![allow(unused_imports)] use actix_service::IntoService; use super::*; use crate::{ dev::ServiceRequest, http::StatusCode, middleware::{self, Condition, Identity, Logger}, test::{self, call_service, init_service, TestRequest}, web, App, HttpResponse, }; #[actix_rt::test] #[cfg(all(feature = "cookies", feature = "__compress"))] async fn test_scope_middleware() { use crate::middleware::Compress; let logger = Logger::default(); let compress = Compress::default(); let srv = init_service( App::new().service( web::scope("app") .wrap(logger) .wrap(Compat::new(compress)) .service(web::resource("/test").route(web::get().to(HttpResponse::Ok))), ), ) .await; let req = TestRequest::with_uri("/app/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] #[cfg(all(feature = "cookies", feature = "__compress"))] async fn test_resource_scope_middleware() { use crate::middleware::Compress; let logger = Logger::default(); let compress = Compress::default(); let srv = init_service( App::new().service( web::resource("app/test") .wrap(Compat::new(logger)) .wrap(Compat::new(compress)) .route(web::get().to(HttpResponse::Ok)), ), ) .await; let req = TestRequest::with_uri("/app/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_condition_scope_middleware() { let srv = |req: ServiceRequest| { Box::pin( async move { Ok(req.into_response(HttpResponse::InternalServerError().finish())) }, ) }; let logger = Logger::default(); let mw = Condition::new(true, Compat::new(logger)) .new_transform(srv.into_service()) .await .unwrap(); let resp = call_service(&mw, TestRequest::default().to_srv_request()).await; assert_eq!(resp.status(), StatusCode::INTERNAL_SERVER_ERROR); } #[actix_rt::test] async fn compat_noop_is_noop() { let srv = test::ok_service(); let mw = Compat::new(Identity) .new_transform(srv.into_service()) .await .unwrap(); let resp = call_service(&mw, TestRequest::default().to_srv_request()).await; assert_eq!(resp.status(), StatusCode::OK); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/test/test_services.rs
actix-web/src/test/test_services.rs
use actix_utils::future::ok; use crate::{ body::BoxBody, dev::{fn_service, Service, ServiceRequest, ServiceResponse}, http::StatusCode, Error, HttpResponseBuilder, }; /// Creates service that always responds with `200 OK` and no body. pub fn ok_service( ) -> impl Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error> { status_service(StatusCode::OK) } /// Creates service that always responds with given status code and no body. pub fn status_service( status_code: StatusCode, ) -> impl Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error> { fn_service(move |req: ServiceRequest| { ok(req.into_response(HttpResponseBuilder::new(status_code).finish())) }) } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `status_service`.")] pub fn simple_service( status_code: StatusCode, ) -> impl Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error> { status_service(status_code) } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `status_service`.")] pub fn default_service( status_code: StatusCode, ) -> impl Service<ServiceRequest, Response = ServiceResponse<BoxBody>, Error = Error> { status_service(status_code) }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/test/test_utils.rs
actix-web/src/test/test_utils.rs
use std::error::Error as StdError; use actix_http::Request; use actix_service::IntoServiceFactory; use serde::de::DeserializeOwned; use crate::{ body::{self, MessageBody}, config::AppConfig, dev::{Service, ServiceFactory}, service::ServiceResponse, web::Bytes, Error, }; /// Initialize service from application builder instance. /// /// # Examples /// ``` /// use actix_service::Service; /// use actix_web::{test, web, App, HttpResponse, http::StatusCode}; /// /// #[actix_web::test] /// async fn test_init_service() { /// let app = test::init_service( /// App::new() /// .service(web::resource("/test").to(|| async { "OK" })) /// ).await; /// /// // Create request object /// let req = test::TestRequest::with_uri("/test").to_request(); /// /// // Execute application /// let res = app.call(req).await.unwrap(); /// assert_eq!(res.status(), StatusCode::OK); /// } /// ``` /// /// # Panics /// Panics if service initialization returns an error. pub async fn init_service<R, S, B, E>( app: R, ) -> impl Service<Request, Response = ServiceResponse<B>, Error = E> where R: IntoServiceFactory<S, Request>, S: ServiceFactory<Request, Config = AppConfig, Response = ServiceResponse<B>, Error = E>, S::InitError: std::fmt::Debug, { try_init_service(app) .await .expect("service initialization failed") } /// Fallible version of [`init_service`] that allows testing initialization errors. pub(crate) async fn try_init_service<R, S, B, E>( app: R, ) -> Result<impl Service<Request, Response = ServiceResponse<B>, Error = E>, S::InitError> where R: IntoServiceFactory<S, Request>, S: ServiceFactory<Request, Config = AppConfig, Response = ServiceResponse<B>, Error = E>, S::InitError: std::fmt::Debug, { let srv = app.into_factory(); srv.new_service(AppConfig::default()).await } /// Calls service and waits for response future completion. /// /// # Examples /// ``` /// use actix_web::{test, web, App, HttpResponse, http::StatusCode}; /// /// #[actix_web::test] /// async fn test_response() { /// let app = test::init_service( /// App::new() /// .service(web::resource("/test").to(|| async { /// HttpResponse::Ok() /// })) /// ).await; /// /// // Create request object /// let req = test::TestRequest::with_uri("/test").to_request(); /// /// // Call application /// let res = test::call_service(&app, req).await; /// assert_eq!(res.status(), StatusCode::OK); /// } /// ``` /// /// # Panics /// Panics if service call returns error. To handle errors use `app.call(req)`. pub async fn call_service<S, R, B, E>(app: &S, req: R) -> S::Response where S: Service<R, Response = ServiceResponse<B>, Error = E>, E: std::fmt::Debug, { app.call(req) .await .expect("test service call returned error") } /// Fallible version of [`call_service`] that allows testing response completion errors. pub async fn try_call_service<S, R, B, E>(app: &S, req: R) -> Result<S::Response, E> where S: Service<R, Response = ServiceResponse<B>, Error = E>, E: std::fmt::Debug, { app.call(req).await } /// Helper function that returns a response body of a TestRequest /// /// # Examples /// ``` /// use actix_web::{test, web, App, HttpResponse, http::header}; /// use bytes::Bytes; /// /// #[actix_web::test] /// async fn test_index() { /// let app = test::init_service( /// App::new().service( /// web::resource("/index.html") /// .route(web::post().to(|| async { /// HttpResponse::Ok().body("welcome!") /// }))) /// ).await; /// /// let req = test::TestRequest::post() /// .uri("/index.html") /// .header(header::CONTENT_TYPE, "application/json") /// .to_request(); /// /// let result = test::call_and_read_body(&app, req).await; /// assert_eq!(result, Bytes::from_static(b"welcome!")); /// } /// ``` /// /// # Panics /// Panics if: /// - service call returns error; /// - body yields an error while it is being read. pub async fn call_and_read_body<S, B>(app: &S, req: Request) -> Bytes where S: Service<Request, Response = ServiceResponse<B>, Error = Error>, B: MessageBody, { let res = call_service(app, req).await; read_body(res).await } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `call_and_read_body`.")] pub async fn read_response<S, B>(app: &S, req: Request) -> Bytes where S: Service<Request, Response = ServiceResponse<B>, Error = Error>, B: MessageBody, { let res = call_service(app, req).await; read_body(res).await } /// Helper function that returns a response body of a ServiceResponse. /// /// # Examples /// ``` /// use actix_web::{test, web, App, HttpResponse, http::header}; /// use bytes::Bytes; /// /// #[actix_web::test] /// async fn test_index() { /// let app = test::init_service( /// App::new().service( /// web::resource("/index.html") /// .route(web::post().to(|| async { /// HttpResponse::Ok().body("welcome!") /// }))) /// ).await; /// /// let req = test::TestRequest::post() /// .uri("/index.html") /// .header(header::CONTENT_TYPE, "application/json") /// .to_request(); /// /// let res = test::call_service(&app, req).await; /// let result = test::read_body(res).await; /// assert_eq!(result, Bytes::from_static(b"welcome!")); /// } /// ``` /// /// # Panics /// Panics if body yields an error while it is being read. pub async fn read_body<B>(res: ServiceResponse<B>) -> Bytes where B: MessageBody, { try_read_body(res) .await .map_err(Into::<Box<dyn StdError>>::into) .expect("error reading test response body") } /// Fallible version of [`read_body`] that allows testing MessageBody reading errors. pub async fn try_read_body<B>(res: ServiceResponse<B>) -> Result<Bytes, <B as MessageBody>::Error> where B: MessageBody, { let body = res.into_body(); body::to_bytes(body).await } /// Helper function that returns a deserialized response body of a ServiceResponse. /// /// # Examples /// ``` /// use actix_web::{App, test, web, HttpResponse, http::header}; /// use serde::{Serialize, Deserialize}; /// /// #[derive(Serialize, Deserialize)] /// pub struct Person { /// id: String, /// name: String, /// } /// /// #[actix_web::test] /// async fn test_post_person() { /// let app = test::init_service( /// App::new().service( /// web::resource("/people") /// .route(web::post().to(|person: web::Json<Person>| async { /// HttpResponse::Ok() /// .json(person)}) /// )) /// ).await; /// /// let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes(); /// /// let res = test::TestRequest::post() /// .uri("/people") /// .header(header::CONTENT_TYPE, "application/json") /// .set_payload(payload) /// .send_request(&mut app) /// .await; /// /// assert!(res.status().is_success()); /// /// let result: Person = test::read_body_json(res).await; /// } /// ``` /// /// # Panics /// Panics if: /// - body yields an error while it is being read; /// - received body is not a valid JSON representation of `T`. pub async fn read_body_json<T, B>(res: ServiceResponse<B>) -> T where B: MessageBody, T: DeserializeOwned, { try_read_body_json(res).await.unwrap_or_else(|err| { panic!( "could not deserialize body into a {}\nerr: {}", std::any::type_name::<T>(), err, ) }) } /// Fallible version of [`read_body_json`] that allows testing response deserialization errors. pub async fn try_read_body_json<T, B>(res: ServiceResponse<B>) -> Result<T, Box<dyn StdError>> where B: MessageBody, T: DeserializeOwned, { let body = try_read_body(res) .await .map_err(Into::<Box<dyn StdError>>::into)?; serde_json::from_slice(&body).map_err(Into::<Box<dyn StdError>>::into) } /// Helper function that returns a deserialized response body of a TestRequest /// /// # Examples /// ``` /// use actix_web::{App, test, web, HttpResponse, http::header}; /// use serde::{Serialize, Deserialize}; /// /// #[derive(Serialize, Deserialize)] /// pub struct Person { /// id: String, /// name: String /// } /// /// #[actix_web::test] /// async fn test_add_person() { /// let app = test::init_service( /// App::new().service( /// web::resource("/people") /// .route(web::post().to(|person: web::Json<Person>| async { /// HttpResponse::Ok() /// .json(person)}) /// )) /// ).await; /// /// let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes(); /// /// let req = test::TestRequest::post() /// .uri("/people") /// .header(header::CONTENT_TYPE, "application/json") /// .set_payload(payload) /// .to_request(); /// /// let result: Person = test::call_and_read_body_json(&mut app, req).await; /// } /// ``` /// /// # Panics /// Panics if: /// - service call returns an error body yields an error while it is being read; /// - body yields an error while it is being read; /// - received body is not a valid JSON representation of `T`. pub async fn call_and_read_body_json<S, B, T>(app: &S, req: Request) -> T where S: Service<Request, Response = ServiceResponse<B>, Error = Error>, B: MessageBody, T: DeserializeOwned, { try_call_and_read_body_json(app, req).await.unwrap() } /// Fallible version of [`call_and_read_body_json`] that allows testing service call errors. pub async fn try_call_and_read_body_json<S, B, T>( app: &S, req: Request, ) -> Result<T, Box<dyn StdError>> where S: Service<Request, Response = ServiceResponse<B>, Error = Error>, B: MessageBody, T: DeserializeOwned, { let res = try_call_service(app, req) .await .map_err(Into::<Box<dyn StdError>>::into)?; try_read_body_json(res).await } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `call_and_read_body_json`.")] pub async fn read_response_json<S, B, T>(app: &S, req: Request) -> T where S: Service<Request, Response = ServiceResponse<B>, Error = Error>, B: MessageBody, T: DeserializeOwned, { call_and_read_body_json(app, req).await } #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use super::*; use crate::{ dev::ServiceRequest, http::header, test::TestRequest, web, App, HttpMessage, HttpResponse, }; #[actix_rt::test] async fn test_request_methods() { let app = init_service( App::new().service( web::resource("/index.html") .route(web::put().to(|| HttpResponse::Ok().body("put!"))) .route(web::patch().to(|| HttpResponse::Ok().body("patch!"))) .route(web::delete().to(|| HttpResponse::Ok().body("delete!"))), ), ) .await; let put_req = TestRequest::put() .uri("/index.html") .insert_header((header::CONTENT_TYPE, "application/json")) .to_request(); let result = call_and_read_body(&app, put_req).await; assert_eq!(result, Bytes::from_static(b"put!")); let patch_req = TestRequest::patch() .uri("/index.html") .insert_header((header::CONTENT_TYPE, "application/json")) .to_request(); let result = call_and_read_body(&app, patch_req).await; assert_eq!(result, Bytes::from_static(b"patch!")); let delete_req = TestRequest::delete().uri("/index.html").to_request(); let result = call_and_read_body(&app, delete_req).await; assert_eq!(result, Bytes::from_static(b"delete!")); } #[derive(Serialize, Deserialize, Debug)] pub struct Person { id: String, name: String, } #[actix_rt::test] async fn test_response_json() { let app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)), ))) .await; let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes(); let req = TestRequest::post() .uri("/people") .insert_header((header::CONTENT_TYPE, "application/json")) .set_payload(payload) .to_request(); let result: Person = call_and_read_body_json(&app, req).await; assert_eq!(&result.id, "12345"); } #[actix_rt::test] async fn test_try_response_json_error() { let app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)), ))) .await; let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes(); let req = TestRequest::post() .uri("/animals") // Not registered to ensure an error occurs. .insert_header((header::CONTENT_TYPE, "application/json")) .set_payload(payload) .to_request(); let result: Result<Person, Box<dyn StdError>> = try_call_and_read_body_json(&app, req).await; assert!(result.is_err()); } #[actix_rt::test] async fn test_body_json() { let app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)), ))) .await; let payload = r#"{"id":"12345","name":"User name"}"#.as_bytes(); let res = TestRequest::post() .uri("/people") .insert_header((header::CONTENT_TYPE, "application/json")) .set_payload(payload) .send_request(&app) .await; let result: Person = read_body_json(res).await; assert_eq!(&result.name, "User name"); } #[actix_rt::test] async fn test_try_body_json_error() { let app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)), ))) .await; // Use a number for id to cause a deserialization error. let payload = r#"{"id":12345,"name":"User name"}"#.as_bytes(); let res = TestRequest::post() .uri("/people") .insert_header((header::CONTENT_TYPE, "application/json")) .set_payload(payload) .send_request(&app) .await; let result: Result<Person, Box<dyn StdError>> = try_read_body_json(res).await; assert!(result.is_err()); } #[actix_rt::test] async fn test_request_response_form() { let app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::Form<Person>| HttpResponse::Ok().json(person)), ))) .await; let payload = Person { id: "12345".to_string(), name: "User name".to_string(), }; let req = TestRequest::post() .uri("/people") .set_form(&payload) .to_request(); assert_eq!(req.content_type(), "application/x-www-form-urlencoded"); let result: Person = call_and_read_body_json(&app, req).await; assert_eq!(&result.id, "12345"); assert_eq!(&result.name, "User name"); } #[actix_rt::test] async fn test_response() { let app = init_service( App::new().service( web::resource("/index.html") .route(web::post().to(|| HttpResponse::Ok().body("welcome!"))), ), ) .await; let req = TestRequest::post() .uri("/index.html") .insert_header((header::CONTENT_TYPE, "application/json")) .to_request(); let result = call_and_read_body(&app, req).await; assert_eq!(result, Bytes::from_static(b"welcome!")); } #[actix_rt::test] async fn test_request_response_json() { let app = init_service(App::new().service(web::resource("/people").route( web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)), ))) .await; let payload = Person { id: "12345".to_string(), name: "User name".to_string(), }; let req = TestRequest::post() .uri("/people") .set_json(&payload) .to_request(); assert_eq!(req.content_type(), "application/json"); let result: Person = call_and_read_body_json(&app, req).await; assert_eq!(&result.id, "12345"); assert_eq!(&result.name, "User name"); } #[actix_rt::test] #[allow(dead_code)] async fn return_opaque_types() { fn test_app() -> App< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<impl MessageBody>, Error = crate::Error, InitError = (), >, > { App::new().service( web::resource("/people").route( web::post().to(|person: web::Json<Person>| HttpResponse::Ok().json(person)), ), ) } async fn test_service( ) -> impl Service<Request, Response = ServiceResponse<impl MessageBody>, Error = crate::Error> { init_service(test_app()).await } async fn compile_test(mut req: Vec<Request>) { let svc = test_service().await; call_service(&svc, req.pop().unwrap()).await; call_and_read_body(&svc, req.pop().unwrap()).await; read_body(call_service(&svc, req.pop().unwrap()).await).await; let _: String = call_and_read_body_json(&svc, req.pop().unwrap()).await; let _: String = read_body_json(call_service(&svc, req.pop().unwrap()).await).await; } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/test/test_request.rs
actix-web/src/test/test_request.rs
use std::{borrow::Cow, net::SocketAddr, rc::Rc}; use actix_http::{test::TestRequest as HttpTestRequest, Request}; use serde::Serialize; #[cfg(feature = "cookies")] use crate::cookie::{Cookie, CookieJar}; use crate::{ app_service::AppInitServiceState, config::AppConfig, data::Data, dev::{Extensions, Path, Payload, ResourceDef, Service, Url}, http::{ header::{ContentType, TryIntoHeaderPair}, Method, Uri, Version, }, rmap::ResourceMap, service::{ServiceRequest, ServiceResponse}, test, web::Bytes, HttpRequest, HttpResponse, }; /// Test `Request` builder. /// /// For unit testing, actix provides a request builder type and a simple handler runner. TestRequest implements a builder-like pattern. /// You can generate various types of request via TestRequest's methods: /// - [`TestRequest::to_request`] creates an [`actix_http::Request`](Request). /// - [`TestRequest::to_srv_request`] creates a [`ServiceRequest`], which is used for testing middlewares and chain adapters. /// - [`TestRequest::to_srv_response`] creates a [`ServiceResponse`]. /// - [`TestRequest::to_http_request`] creates an [`HttpRequest`], which is used for testing handlers. /// /// ``` /// use actix_web::{test, HttpRequest, HttpResponse, HttpMessage}; /// use actix_web::http::{header, StatusCode}; /// /// async fn handler(req: HttpRequest) -> HttpResponse { /// if let Some(hdr) = req.headers().get(header::CONTENT_TYPE) { /// HttpResponse::Ok().into() /// } else { /// HttpResponse::BadRequest().into() /// } /// } /// /// #[actix_web::test] /// # // force rustdoc to display the correct thing and also compile check the test /// # async fn _test() {} /// async fn test_index() { /// let req = test::TestRequest::default() /// .insert_header(header::ContentType::plaintext()) /// .to_http_request(); /// /// let resp = handler(req).await; /// assert_eq!(resp.status(), StatusCode::OK); /// /// let req = test::TestRequest::default().to_http_request(); /// let resp = handler(req).await; /// assert_eq!(resp.status(), StatusCode::BAD_REQUEST); /// } /// ``` pub struct TestRequest { req: HttpTestRequest, rmap: ResourceMap, config: AppConfig, path: Path<Url>, peer_addr: Option<SocketAddr>, app_data: Extensions, #[cfg(feature = "cookies")] cookies: CookieJar, } impl Default for TestRequest { fn default() -> TestRequest { TestRequest { req: HttpTestRequest::default(), rmap: ResourceMap::new(ResourceDef::new("")), config: AppConfig::default(), path: Path::new(Url::new(Uri::default())), peer_addr: None, app_data: Extensions::new(), #[cfg(feature = "cookies")] cookies: CookieJar::new(), } } } #[allow(clippy::wrong_self_convention)] impl TestRequest { /// Constructs test request and sets request URI. pub fn with_uri(uri: &str) -> TestRequest { TestRequest::default().uri(uri) } /// Constructs test request with GET method. pub fn get() -> TestRequest { TestRequest::default().method(Method::GET) } /// Constructs test request with POST method. pub fn post() -> TestRequest { TestRequest::default().method(Method::POST) } /// Constructs test request with PUT method. pub fn put() -> TestRequest { TestRequest::default().method(Method::PUT) } /// Constructs test request with PATCH method. pub fn patch() -> TestRequest { TestRequest::default().method(Method::PATCH) } /// Constructs test request with DELETE method. pub fn delete() -> TestRequest { TestRequest::default().method(Method::DELETE) } /// Sets HTTP version of this request. pub fn version(mut self, ver: Version) -> Self { self.req.version(ver); self } /// Sets method of this request. pub fn method(mut self, meth: Method) -> Self { self.req.method(meth); self } /// Sets URI of this request. pub fn uri(mut self, path: &str) -> Self { self.req.uri(path); self } /// Inserts a header, replacing any that were set with an equivalent field name. pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self { self.req.insert_header(header); self } /// Appends a header, keeping any that were set with an equivalent field name. pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self { self.req.append_header(header); self } /// Sets cookie for this request. #[cfg(feature = "cookies")] pub fn cookie(mut self, cookie: Cookie<'_>) -> Self { self.cookies.add(cookie.into_owned()); self } /// Sets request path pattern parameter. /// /// # Examples /// /// ``` /// use actix_web::test::TestRequest; /// /// let req = TestRequest::default().param("foo", "bar"); /// let req = TestRequest::default().param("foo".to_owned(), "bar".to_owned()); /// ``` pub fn param( mut self, name: impl Into<Cow<'static, str>>, value: impl Into<Cow<'static, str>>, ) -> Self { self.path.add_static(name, value); self } /// Sets peer address. pub fn peer_addr(mut self, addr: SocketAddr) -> Self { self.peer_addr = Some(addr); self } /// Sets request payload. pub fn set_payload(mut self, data: impl Into<Bytes>) -> Self { self.req.set_payload(data); self } /// Serializes `data` to a URL encoded form and set it as the request payload. /// /// The `Content-Type` header is set to `application/x-www-form-urlencoded`. pub fn set_form(mut self, data: impl Serialize) -> Self { let bytes = serde_urlencoded::to_string(&data) .expect("Failed to serialize test data as a urlencoded form"); self.req.set_payload(bytes); self.req.insert_header(ContentType::form_url_encoded()); self } /// Serializes `data` to JSON and set it as the request payload. /// /// The `Content-Type` header is set to `application/json`. pub fn set_json(mut self, data: impl Serialize) -> Self { let bytes = serde_json::to_string(&data).expect("Failed to serialize test data to json"); self.req.set_payload(bytes); self.req.insert_header(ContentType::json()); self } /// Inserts application data. /// /// This is equivalent of `App::app_data()` method for testing purpose. pub fn app_data<T: 'static>(mut self, data: T) -> Self { self.app_data.insert(data); self } /// Inserts application data. /// /// This is equivalent of `App::data()` method for testing purpose. #[doc(hidden)] pub fn data<T: 'static>(mut self, data: T) -> Self { self.app_data.insert(Data::new(data)); self } /// Sets resource map. #[cfg(test)] pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self { self.rmap = rmap; self } /// Finalizes test request. /// /// This request builder will be useless after calling `finish()`. fn finish(&mut self) -> Request { // mut used when cookie feature is enabled #[allow(unused_mut)] let mut req = self.req.finish(); #[cfg(feature = "cookies")] { use actix_http::header::{HeaderValue, COOKIE}; let cookie: String = self .cookies .delta() // ensure only name=value is written to cookie header .map(|c| c.stripped().encoded().to_string()) .collect::<Vec<_>>() .join("; "); if !cookie.is_empty() { req.headers_mut() .insert(COOKIE, HeaderValue::from_str(&cookie).unwrap()); } } req } /// Finalizes request creation and returns `Request` instance. pub fn to_request(mut self) -> Request { let mut req = self.finish(); req.head_mut().peer_addr = self.peer_addr; req } /// Finalizes request creation and returns `ServiceRequest` instance. pub fn to_srv_request(mut self) -> ServiceRequest { let (mut head, payload) = self.finish().into_parts(); head.peer_addr = self.peer_addr; self.path.get_mut().update(&head.uri); let app_state = AppInitServiceState::new(Rc::new(self.rmap), self.config.clone()); ServiceRequest::new( HttpRequest::new( self.path, head, app_state, Rc::new(self.app_data), None, Default::default(), ), payload, ) } /// Finalizes request creation and returns `ServiceResponse` instance. pub fn to_srv_response<B>(self, res: HttpResponse<B>) -> ServiceResponse<B> { self.to_srv_request().into_response(res) } /// Finalizes request creation and returns `HttpRequest` instance. pub fn to_http_request(mut self) -> HttpRequest { let (mut head, _) = self.finish().into_parts(); head.peer_addr = self.peer_addr; self.path.get_mut().update(&head.uri); let app_state = AppInitServiceState::new(Rc::new(self.rmap), self.config.clone()); HttpRequest::new( self.path, head, app_state, Rc::new(self.app_data), None, Default::default(), ) } /// Finalizes request creation and returns `HttpRequest` and `Payload` pair. pub fn to_http_parts(mut self) -> (HttpRequest, Payload) { let (mut head, payload) = self.finish().into_parts(); head.peer_addr = self.peer_addr; self.path.get_mut().update(&head.uri); let app_state = AppInitServiceState::new(Rc::new(self.rmap), self.config.clone()); let req = HttpRequest::new( self.path, head, app_state, Rc::new(self.app_data), None, Default::default(), ); (req, payload) } /// Finalizes request creation, calls service, and waits for response future completion. pub async fn send_request<S, B, E>(self, app: &S) -> S::Response where S: Service<Request, Response = ServiceResponse<B>, Error = E>, E: std::fmt::Debug, { let req = self.to_request(); test::call_service(app, req).await } #[cfg(test)] pub fn set_server_hostname(&mut self, host: &str) { self.config.set_host(host) } } #[cfg(test)] mod tests { use std::time::SystemTime; use super::*; use crate::{http::header, test::init_service, web, App, Error, Responder}; #[actix_rt::test] async fn test_basics() { let req = TestRequest::default() .version(Version::HTTP_2) .insert_header(header::ContentType::json()) .insert_header(header::Date(SystemTime::now().into())) .param("test", "123") .data(10u32) .app_data(20u64) .peer_addr("127.0.0.1:8081".parse().unwrap()) .to_http_request(); assert!(req.headers().contains_key(header::CONTENT_TYPE)); assert!(req.headers().contains_key(header::DATE)); assert_eq!( req.head().peer_addr, Some("127.0.0.1:8081".parse().unwrap()) ); assert_eq!(&req.match_info()["test"], "123"); assert_eq!(req.version(), Version::HTTP_2); let data = req.app_data::<Data<u32>>().unwrap(); assert!(req.app_data::<Data<u64>>().is_none()); assert_eq!(*data.get_ref(), 10); assert!(req.app_data::<u32>().is_none()); let data = req.app_data::<u64>().unwrap(); assert_eq!(*data, 20); } #[actix_rt::test] async fn test_send_request() { let app = init_service( App::new().service( web::resource("/index.html") .route(web::get().to(|| HttpResponse::Ok().body("welcome!"))), ), ) .await; let resp = TestRequest::get() .uri("/index.html") .send_request(&app) .await; let result = test::read_body(resp).await; assert_eq!(result, Bytes::from_static(b"welcome!")); } #[actix_rt::test] async fn test_async_with_block() { async fn async_with_block() -> Result<HttpResponse, Error> { let res = web::block(move || Some(4usize).ok_or("wrong")).await; match res { Ok(value) => Ok(HttpResponse::Ok() .content_type("text/plain") .body(format!("Async with block value: {:?}", value))), Err(_) => panic!("Unexpected"), } } let app = init_service(App::new().service(web::resource("/index.html").to(async_with_block))) .await; let req = TestRequest::post().uri("/index.html").to_request(); let res = app.call(req).await.unwrap(); assert!(res.status().is_success()); } // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_server_data() { async fn handler(data: web::Data<usize>) -> impl Responder { assert_eq!(**data, 10); HttpResponse::Ok() } let app = init_service( App::new() .data(10usize) .service(web::resource("/index.html").to(handler)), ) .await; let req = TestRequest::post().uri("/index.html").to_request(); let res = app.call(req).await.unwrap(); assert!(res.status().is_success()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/test/mod.rs
actix-web/src/test/mod.rs
//! Various helpers for Actix applications to use during testing. //! //! # Initializing A Test Service //! - [`init_service`] //! //! # Off-The-Shelf Test Services //! - [`ok_service`] //! - [`status_service`] //! //! # Calling Test Service //! - [`TestRequest`] //! - [`call_service`] //! - [`try_call_service`] //! - [`call_and_read_body`] //! - [`call_and_read_body_json`] //! - [`try_call_and_read_body_json`] //! //! # Reading Response Payloads //! - [`read_body`] //! - [`try_read_body`] //! - [`read_body_json`] //! - [`try_read_body_json`] // TODO: more docs on generally how testing works with these parts pub use actix_http::test::TestBuffer; mod test_request; mod test_services; mod test_utils; #[allow(deprecated)] pub use self::test_services::{default_service, ok_service, simple_service, status_service}; #[cfg(test)] pub(crate) use self::test_utils::try_init_service; #[allow(deprecated)] pub use self::test_utils::{read_response, read_response_json}; pub use self::{ test_request::TestRequest, test_utils::{ call_and_read_body, call_and_read_body_json, call_service, init_service, read_body, read_body_json, try_call_and_read_body_json, try_call_service, try_read_body, try_read_body_json, }, }; /// Reduces boilerplate code when testing expected response payloads. /// /// Must be used inside an async test. Works for both `ServiceRequest` and `HttpRequest`. /// /// # Examples /// /// ``` /// use actix_web::{http::StatusCode, HttpResponse}; /// /// let res = HttpResponse::with_body(StatusCode::OK, "http response"); /// assert_body_eq!(res, b"http response"); /// ``` #[cfg(test)] macro_rules! assert_body_eq { ($res:ident, $expected:expr) => { assert_eq!( ::actix_http::body::to_bytes($res.into_body()) .await .expect("error reading test response body"), ::bytes::Bytes::from_static($expected), ) }; } #[cfg(test)] pub(crate) use assert_body_eq; #[cfg(test)] mod tests { use super::*; use crate::{http::StatusCode, service::ServiceResponse, HttpResponse}; #[actix_rt::test] async fn assert_body_works_for_service_and_regular_response() { let res = HttpResponse::with_body(StatusCode::OK, "http response"); assert_body_eq!(res, b"http response"); let req = TestRequest::default().to_http_request(); let res = HttpResponse::with_body(StatusCode::OK, "service response"); let res = ServiceResponse::new(req, res); assert_body_eq!(res, b"service response"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/html.rs
actix-web/src/types/html.rs
//! Semantic HTML responder. See [`Html`]. use crate::{ http::{ header::{self, ContentType, TryIntoHeaderValue}, StatusCode, }, HttpRequest, HttpResponse, Responder, }; /// Semantic HTML responder. /// /// When used as a responder, creates a 200 OK response, sets the correct HTML content type, and /// uses the string passed to [`Html::new()`] as the body. /// /// ``` /// # use actix_web::web::Html; /// Html::new("<p>Hello, World!</p>") /// # ; /// ``` #[derive(Debug, Clone, PartialEq, Hash)] pub struct Html(String); impl Html { /// Constructs a new `Html` responder. pub fn new(html: impl Into<String>) -> Self { Self(html.into()) } } impl Responder for Html { type Body = String; fn respond_to(self, _req: &HttpRequest) -> HttpResponse<Self::Body> { let mut res = HttpResponse::with_body(StatusCode::OK, self.0); res.headers_mut().insert( header::CONTENT_TYPE, ContentType::html().try_into_value().unwrap(), ); res } } #[cfg(test)] mod tests { use super::*; use crate::test::TestRequest; #[test] fn responder() { let req = TestRequest::default().to_http_request(); let res = Html::new("<p>Hello, World!</p>"); let res = res.respond_to(&req); assert!(res.status().is_success()); assert!(res .headers() .get(header::CONTENT_TYPE) .unwrap() .to_str() .unwrap() .starts_with("text/html")); assert!(res.body().starts_with("<p>")); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/path.rs
actix-web/src/types/path.rs
//! For path segment extractor documentation, see [`Path`]. use std::sync::Arc; use actix_router::PathDeserializer; use actix_utils::future::{ready, Ready}; use derive_more::{AsRef, Deref, DerefMut, Display, From}; use serde::de; use crate::{ dev::Payload, error::{Error, ErrorNotFound, PathError}, web::Data, FromRequest, HttpRequest, }; /// Extract typed data from request path segments. /// /// Use [`PathConfig`] to configure extraction option. /// /// Unlike, [`HttpRequest::match_info`], this extractor will fully percent-decode dynamic segments, /// including `/`, `%`, and `+`. /// /// # Examples /// ``` /// use actix_web::{get, web}; /// /// // extract path info from "/{name}/{count}/index.html" into tuple /// // {name} - deserialize a String /// // {count} - deserialize a u32 /// #[get("/{name}/{count}/index.html")] /// async fn index(path: web::Path<(String, u32)>) -> String { /// let (name, count) = path.into_inner(); /// format!("Welcome {}! {}", name, count) /// } /// ``` /// /// Path segments also can be deserialized into any type that implements [`serde::Deserialize`]. /// Path segment labels will be matched with struct field names. /// /// ``` /// use actix_web::{get, web}; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Info { /// name: String, /// } /// /// // extract `Info` from a path using serde /// #[get("/{name}")] /// async fn index(info: web::Path<Info>) -> String { /// format!("Welcome {}!", info.name) /// } /// ``` #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Deref, DerefMut, AsRef, Display, From)] pub struct Path<T>(T); impl<T> Path<T> { /// Unwrap into inner `T` value. pub fn into_inner(self) -> T { self.0 } } /// See [here](#Examples) for example of usage as an extractor. impl<T> FromRequest for Path<T> where T: de::DeserializeOwned, { type Error = Error; type Future = Ready<Result<Self, Self::Error>>; #[inline] fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { let error_handler = req .app_data::<PathConfig>() .or_else(|| req.app_data::<Data<PathConfig>>().map(Data::get_ref)) .and_then(|c| c.err_handler.clone()); ready( de::Deserialize::deserialize(PathDeserializer::new(req.match_info())) .map(Path) .map_err(move |err| { log::debug!( "Failed during Path extractor deserialization. \ Request path: {:?}", req.path() ); if let Some(error_handler) = error_handler { let err = PathError::Deserialize(err); (error_handler)(err, req) } else { ErrorNotFound(err) } }), ) } } /// Path extractor configuration /// /// ``` /// use actix_web::web::PathConfig; /// use actix_web::{error, web, App, FromRequest, HttpResponse}; /// use serde::Deserialize; /// /// #[derive(Deserialize, Debug)] /// enum Folder { /// #[serde(rename = "inbox")] /// Inbox, /// /// #[serde(rename = "outbox")] /// Outbox, /// } /// /// // deserialize `Info` from request's path /// async fn index(folder: web::Path<Folder>) -> String { /// format!("Selected folder: {:?}!", folder) /// } /// /// let app = App::new().service( /// web::resource("/messages/{folder}") /// .app_data(PathConfig::default().error_handler(|err, req| { /// error::InternalError::from_response( /// err, /// HttpResponse::Conflict().into(), /// ) /// .into() /// })) /// .route(web::post().to(index)), /// ); /// ``` #[derive(Clone, Default)] pub struct PathConfig { #[allow(clippy::type_complexity)] err_handler: Option<Arc<dyn Fn(PathError, &HttpRequest) -> Error + Send + Sync>>, } impl PathConfig { /// Set custom error handler. pub fn error_handler<F>(mut self, f: F) -> Self where F: Fn(PathError, &HttpRequest) -> Error + Send + Sync + 'static, { self.err_handler = Some(Arc::new(f)); self } } #[cfg(test)] mod tests { use actix_router::ResourceDef; use derive_more::Display; use serde::Deserialize; use super::*; use crate::{error, http, test::TestRequest, HttpResponse}; #[derive(Deserialize, Debug, Display)] #[display("MyStruct({}, {})", key, value)] struct MyStruct { key: String, value: String, } #[derive(Deserialize)] struct Test2 { key: String, value: u32, } #[actix_rt::test] async fn test_extract_path_single() { let resource = ResourceDef::new("/{value}/"); let mut req = TestRequest::with_uri("/32/").to_srv_request(); resource.capture_match_info(req.match_info_mut()); let (req, mut pl) = req.into_parts(); assert_eq!(*Path::<i8>::from_request(&req, &mut pl).await.unwrap(), 32); assert!(Path::<MyStruct>::from_request(&req, &mut pl).await.is_err()); } #[allow(clippy::let_unit_value)] #[actix_rt::test] async fn test_tuple_extract() { let resource = ResourceDef::new("/{key}/{value}/"); let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request(); resource.capture_match_info(req.match_info_mut()); let (req, mut pl) = req.into_parts(); let (Path(res),) = <(Path<(String, String)>,)>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(res.0, "name"); assert_eq!(res.1, "user1"); let (Path(a), Path(b)) = <(Path<(String, String)>, Path<(String, String)>)>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(a.0, "name"); assert_eq!(a.1, "user1"); assert_eq!(b.0, "name"); assert_eq!(b.1, "user1"); let () = <()>::from_request(&req, &mut pl).await.unwrap(); } #[actix_rt::test] async fn test_request_extract() { let mut req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request(); let resource = ResourceDef::new("/{key}/{value}/"); resource.capture_match_info(req.match_info_mut()); let (req, mut pl) = req.into_parts(); let mut s = Path::<MyStruct>::from_request(&req, &mut pl).await.unwrap(); assert_eq!(s.key, "name"); assert_eq!(s.value, "user1"); s.value = "user2".to_string(); assert_eq!(s.value, "user2"); assert_eq!( format!("{}, {:?}", s, s), "MyStruct(name, user2), Path(MyStruct { key: \"name\", value: \"user2\" })" ); let s = s.into_inner(); assert_eq!(s.value, "user2"); let Path(s) = Path::<(String, String)>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(s.0, "name"); assert_eq!(s.1, "user1"); let mut req = TestRequest::with_uri("/name/32/").to_srv_request(); let resource = ResourceDef::new("/{key}/{value}/"); resource.capture_match_info(req.match_info_mut()); let (req, mut pl) = req.into_parts(); let s = Path::<Test2>::from_request(&req, &mut pl).await.unwrap(); assert_eq!(s.as_ref().key, "name"); assert_eq!(s.value, 32); let Path(s) = Path::<(String, u8)>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(s.0, "name"); assert_eq!(s.1, 32); let res = Path::<Vec<String>>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(res[0], "name".to_owned()); assert_eq!(res[1], "32".to_owned()); } #[actix_rt::test] async fn paths_decoded() { let resource = ResourceDef::new("/{key}/{value}"); let mut req = TestRequest::with_uri("/na%2Bme/us%2Fer%254%32").to_srv_request(); resource.capture_match_info(req.match_info_mut()); let (req, mut pl) = req.into_parts(); let path_items = Path::<MyStruct>::from_request(&req, &mut pl).await.unwrap(); assert_eq!(path_items.key, "na+me"); assert_eq!(path_items.value, "us/er%42"); assert_eq!(req.match_info().as_str(), "/na%2Bme/us%2Fer%2542"); } #[actix_rt::test] async fn test_custom_err_handler() { let (req, mut pl) = TestRequest::with_uri("/name/user1/") .app_data(PathConfig::default().error_handler(|err, _| { error::InternalError::from_response(err, HttpResponse::Conflict().finish()).into() })) .to_http_parts(); let s = Path::<(usize,)>::from_request(&req, &mut pl) .await .unwrap_err(); let res = HttpResponse::from_error(s); assert_eq!(res.status(), http::StatusCode::CONFLICT); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/form.rs
actix-web/src/types/form.rs
//! For URL encoded form helper documentation, see [`Form`]. use std::{ borrow::Cow, fmt, future::Future, ops, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_http::Payload; use bytes::BytesMut; use encoding_rs::{Encoding, UTF_8}; use futures_core::{future::LocalBoxFuture, ready}; use futures_util::{FutureExt as _, StreamExt as _}; use serde::{de::DeserializeOwned, Serialize}; #[cfg(feature = "__compress")] use crate::dev::Decompress; use crate::{ body::EitherBody, error::UrlencodedError, extract::FromRequest, http::header::CONTENT_LENGTH, web, Error, HttpMessage, HttpRequest, HttpResponse, Responder, }; /// URL encoded payload extractor and responder. /// /// `Form` has two uses: URL encoded responses, and extracting typed data from URL request payloads. /// /// # Extractor /// To extract typed data from a request body, the inner type `T` must implement the /// [`DeserializeOwned`] trait. /// /// Use [`FormConfig`] to configure extraction options. /// /// ## Examples /// ``` /// use actix_web::{post, web}; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Info { /// name: String, /// } /// /// // This handler is only called if: /// // - request headers declare the content type as `application/x-www-form-urlencoded` /// // - request payload deserializes into an `Info` struct from the URL encoded format /// #[post("/")] /// async fn index(web::Form(form): web::Form<Info>) -> String { /// format!("Welcome {}!", form.name) /// } /// ``` /// /// # Responder /// The `Form` type also allows you to create URL encoded responses by returning a value of type /// `Form<T>` where `T` is the type to be URL encoded, as long as `T` implements [`Serialize`]. /// /// ## Examples /// ``` /// use actix_web::{get, web}; /// use serde::Serialize; /// /// #[derive(Serialize)] /// struct SomeForm { /// name: String, /// age: u8 /// } /// /// // Response will have: /// // - status: 200 OK /// // - header: `Content-Type: application/x-www-form-urlencoded` /// // - body: `name=actix&age=123` /// #[get("/")] /// async fn index() -> web::Form<SomeForm> { /// web::Form(SomeForm { /// name: "actix".to_owned(), /// age: 123 /// }) /// } /// ``` /// /// # Panics /// URL encoded forms consist of unordered `key=value` pairs, therefore they cannot be decoded into /// any type which depends upon data ordering (eg. tuples). Trying to do so will result in a panic. #[derive(PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Form<T>(pub T); impl<T> Form<T> { /// Unwrap into inner `T` value. pub fn into_inner(self) -> T { self.0 } } impl<T> ops::Deref for Form<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T> ops::DerefMut for Form<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } impl<T> Serialize for Form<T> where T: Serialize, { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } /// See [here](#extractor) for example of usage as an extractor. impl<T> FromRequest for Form<T> where T: DeserializeOwned + 'static, { type Error = Error; type Future = FormExtractFut<T>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { let FormConfig { limit, err_handler } = FormConfig::from_req(req).clone(); FormExtractFut { fut: UrlEncoded::new(req, payload).limit(limit), req: req.clone(), err_handler, } } } type FormErrHandler = Option<Rc<dyn Fn(UrlencodedError, &HttpRequest) -> Error>>; pub struct FormExtractFut<T> { fut: UrlEncoded<T>, err_handler: FormErrHandler, req: HttpRequest, } impl<T> Future for FormExtractFut<T> where T: DeserializeOwned + 'static, { type Output = Result<Form<T>, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); let res = ready!(Pin::new(&mut this.fut).poll(cx)); let res = match res { Err(err) => match &this.err_handler { Some(err_handler) => Err((err_handler)(err, &this.req)), None => Err(err.into()), }, Ok(item) => Ok(Form(item)), }; Poll::Ready(res) } } impl<T: fmt::Display> fmt::Display for Form<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } /// See [here](#responder) for example of usage as a handler return type. impl<T: Serialize> Responder for Form<T> { type Body = EitherBody<String>; fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> { match serde_urlencoded::to_string(&self.0) { Ok(body) => match HttpResponse::Ok() .content_type(mime::APPLICATION_WWW_FORM_URLENCODED) .message_body(body) { Ok(res) => res.map_into_left_body(), Err(err) => HttpResponse::from_error(err).map_into_right_body(), }, Err(err) => { HttpResponse::from_error(UrlencodedError::Serialize(err)).map_into_right_body() } } } } /// [`Form`] extractor configuration. /// /// ``` /// use actix_web::{post, web, App, FromRequest, Result}; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Info { /// username: String, /// } /// /// // Custom `FormConfig` is applied to App. /// // Max payload size for URL encoded forms is set to 4kB. /// #[post("/")] /// async fn index(form: web::Form<Info>) -> Result<String> { /// Ok(format!("Welcome {}!", form.username)) /// } /// /// App::new() /// .app_data(web::FormConfig::default().limit(4096)) /// .service(index); /// ``` #[derive(Clone)] pub struct FormConfig { limit: usize, err_handler: FormErrHandler, } impl FormConfig { /// Set maximum accepted payload size. By default this limit is 16kB. pub fn limit(mut self, limit: usize) -> Self { self.limit = limit; self } /// Set custom error handler pub fn error_handler<F>(mut self, f: F) -> Self where F: Fn(UrlencodedError, &HttpRequest) -> Error + 'static, { self.err_handler = Some(Rc::new(f)); self } /// Extract payload config from app data. /// /// Checks both `T` and `Data<T>`, in that order, and falls back to the default payload config. fn from_req(req: &HttpRequest) -> &Self { req.app_data::<Self>() .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref())) .unwrap_or(&DEFAULT_CONFIG) } } /// Allow shared refs used as default. const DEFAULT_CONFIG: FormConfig = FormConfig { limit: 16_384, // 2^14 bytes (~16kB) err_handler: None, }; impl Default for FormConfig { fn default() -> Self { DEFAULT_CONFIG } } /// Future that resolves to some `T` when parsed from a URL encoded payload. /// /// Form can be deserialized from any type `T` that implements [`serde::Deserialize`]. /// /// Returns error if: /// - content type is not `application/x-www-form-urlencoded` /// - content length is greater than [limit](UrlEncoded::limit()) pub struct UrlEncoded<T> { #[cfg(feature = "__compress")] stream: Option<Decompress<Payload>>, #[cfg(not(feature = "__compress"))] stream: Option<Payload>, limit: usize, length: Option<usize>, encoding: &'static Encoding, err: Option<UrlencodedError>, fut: Option<LocalBoxFuture<'static, Result<T, UrlencodedError>>>, } #[allow(clippy::borrow_interior_mutable_const)] impl<T> UrlEncoded<T> { /// Create a new future to decode a URL encoded request payload. pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self { // check content type if req.content_type().to_lowercase() != "application/x-www-form-urlencoded" { return Self::err(UrlencodedError::ContentType); } let encoding = match req.encoding() { Ok(enc) => enc, Err(_) => return Self::err(UrlencodedError::ContentType), }; let mut len = None; if let Some(l) = req.headers().get(&CONTENT_LENGTH) { if let Ok(s) = l.to_str() { if let Ok(l) = s.parse::<usize>() { len = Some(l) } else { return Self::err(UrlencodedError::UnknownLength); } } else { return Self::err(UrlencodedError::UnknownLength); } }; let payload = { cfg_if::cfg_if! { if #[cfg(feature = "__compress")] { Decompress::from_headers(payload.take(), req.headers()) } else { payload.take() } } }; UrlEncoded { encoding, stream: Some(payload), limit: 32_768, length: len, fut: None, err: None, } } fn err(err: UrlencodedError) -> Self { UrlEncoded { stream: None, limit: 32_768, fut: None, err: Some(err), length: None, encoding: UTF_8, } } /// Set maximum accepted payload size. The default limit is 256kB. pub fn limit(mut self, limit: usize) -> Self { self.limit = limit; self } } impl<T> Future for UrlEncoded<T> where T: DeserializeOwned + 'static, { type Output = Result<T, UrlencodedError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { if let Some(ref mut fut) = self.fut { return Pin::new(fut).poll(cx); } if let Some(err) = self.err.take() { return Poll::Ready(Err(err)); } // payload size let limit = self.limit; if let Some(len) = self.length.take() { if len > limit { return Poll::Ready(Err(UrlencodedError::Overflow { size: len, limit })); } } // future let encoding = self.encoding; let mut stream = self.stream.take().unwrap(); self.fut = Some( async move { let mut body = BytesMut::with_capacity(8192); while let Some(item) = stream.next().await { let chunk = item?; if (body.len() + chunk.len()) > limit { return Err(UrlencodedError::Overflow { size: body.len() + chunk.len(), limit, }); } else { body.extend_from_slice(&chunk); } } if encoding == UTF_8 { serde_urlencoded::from_bytes::<T>(&body).map_err(UrlencodedError::Parse) } else { let body = encoding .decode_without_bom_handling_and_without_replacement(&body) .map(Cow::into_owned) .ok_or(UrlencodedError::Encoding)?; serde_urlencoded::from_str::<T>(&body).map_err(UrlencodedError::Parse) } } .boxed_local(), ); self.poll(cx) } } #[cfg(test)] mod tests { use bytes::Bytes; use serde::{Deserialize, Serialize}; use super::*; use crate::{ http::{ header::{HeaderValue, CONTENT_TYPE}, StatusCode, }, test::{assert_body_eq, TestRequest}, }; #[derive(Deserialize, Serialize, Debug, PartialEq)] struct Info { hello: String, counter: i64, } #[actix_rt::test] async fn test_form() { let (req, mut pl) = TestRequest::default() .insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((CONTENT_LENGTH, 11)) .set_payload(Bytes::from_static(b"hello=world&counter=123")) .to_http_parts(); let Form(s) = Form::<Info>::from_request(&req, &mut pl).await.unwrap(); assert_eq!( s, Info { hello: "world".into(), counter: 123 } ); } fn eq(err: UrlencodedError, other: UrlencodedError) -> bool { match err { UrlencodedError::Overflow { .. } => { matches!(other, UrlencodedError::Overflow { .. }) } UrlencodedError::UnknownLength => matches!(other, UrlencodedError::UnknownLength), UrlencodedError::ContentType => matches!(other, UrlencodedError::ContentType), _ => false, } } #[actix_rt::test] async fn test_urlencoded_error() { let (req, mut pl) = TestRequest::default() .insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((CONTENT_LENGTH, "xxxx")) .to_http_parts(); let info = UrlEncoded::<Info>::new(&req, &mut pl).await; assert!(eq(info.err().unwrap(), UrlencodedError::UnknownLength)); let (req, mut pl) = TestRequest::default() .insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((CONTENT_LENGTH, "1000000")) .to_http_parts(); let info = UrlEncoded::<Info>::new(&req, &mut pl).await; assert!(eq( info.err().unwrap(), UrlencodedError::Overflow { size: 0, limit: 0 } )); let (req, mut pl) = TestRequest::default() .insert_header((CONTENT_TYPE, "text/plain")) .insert_header((CONTENT_LENGTH, 10)) .to_http_parts(); let info = UrlEncoded::<Info>::new(&req, &mut pl).await; assert!(eq(info.err().unwrap(), UrlencodedError::ContentType)); } #[actix_rt::test] async fn test_urlencoded() { let (req, mut pl) = TestRequest::default() .insert_header((CONTENT_TYPE, "application/x-www-form-urlencoded")) .insert_header((CONTENT_LENGTH, 11)) .set_payload(Bytes::from_static(b"hello=world&counter=123")) .to_http_parts(); let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap(); assert_eq!( info, Info { hello: "world".to_owned(), counter: 123 } ); let (req, mut pl) = TestRequest::default() .insert_header(( CONTENT_TYPE, "application/x-www-form-urlencoded; charset=utf-8", )) .insert_header((CONTENT_LENGTH, 11)) .set_payload(Bytes::from_static(b"hello=world&counter=123")) .to_http_parts(); let info = UrlEncoded::<Info>::new(&req, &mut pl).await.unwrap(); assert_eq!( info, Info { hello: "world".to_owned(), counter: 123 } ); } #[actix_rt::test] async fn test_responder() { let req = TestRequest::default().to_http_request(); let form = Form(Info { hello: "world".to_string(), counter: 123, }); let res = form.respond_to(&req); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("application/x-www-form-urlencoded") ); assert_body_eq!(res, b"hello=world&counter=123"); } #[actix_rt::test] async fn test_with_config_in_data_wrapper() { let ctype = HeaderValue::from_static("application/x-www-form-urlencoded"); let (req, mut pl) = TestRequest::default() .insert_header((CONTENT_TYPE, ctype)) .insert_header((CONTENT_LENGTH, HeaderValue::from_static("20"))) .set_payload(Bytes::from_static(b"hello=test&counter=4")) .app_data(web::Data::new(FormConfig::default().limit(10))) .to_http_parts(); let s = Form::<Info>::from_request(&req, &mut pl).await; assert!(s.is_err()); let err_str = s.err().unwrap().to_string(); assert!(err_str.starts_with("URL encoded payload is larger")); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/json.rs
actix-web/src/types/json.rs
//! For JSON helper documentation, see [`Json`]. use std::{ fmt, future::Future, marker::PhantomData, ops, pin::Pin, sync::Arc, task::{Context, Poll}, }; use actix_http::Payload; use bytes::BytesMut; use futures_core::{ready, Stream as _}; use serde::{de::DeserializeOwned, Serialize}; #[cfg(feature = "__compress")] use crate::dev::Decompress; use crate::{ body::EitherBody, error::{Error, JsonPayloadError}, extract::FromRequest, http::header::{ContentLength, Header as _}, request::HttpRequest, web, HttpMessage, HttpResponse, Responder, }; /// JSON extractor and responder. /// /// `Json` has two uses: JSON responses, and extracting typed data from JSON request payloads. /// /// # Extractor /// To extract typed data from a request body, the inner type `T` must implement the /// [`serde::Deserialize`] trait. /// /// Use [`JsonConfig`] to configure extraction options. /// /// ``` /// use actix_web::{post, web, App}; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Info { /// username: String, /// } /// /// /// deserialize `Info` from request's body /// #[post("/")] /// async fn index(info: web::Json<Info>) -> String { /// format!("Welcome {}!", info.username) /// } /// ``` /// /// # Responder /// The `Json` type JSON formatted responses. A handler may return a value of type /// `Json<T>` where `T` is the type of a structure to serialize into JSON. The type `T` must /// implement [`serde::Serialize`]. /// /// ``` /// use actix_web::{post, web, HttpRequest}; /// use serde::Serialize; /// /// #[derive(Serialize)] /// struct Info { /// name: String, /// } /// /// #[post("/{name}")] /// async fn index(req: HttpRequest) -> web::Json<Info> { /// web::Json(Info { /// name: req.match_info().get("name").unwrap().to_owned(), /// }) /// } /// ``` #[derive(Debug)] pub struct Json<T>(pub T); impl<T> Json<T> { /// Unwrap into inner `T` value. pub fn into_inner(self) -> T { self.0 } } impl<T> ops::Deref for Json<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T> ops::DerefMut for Json<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } impl<T: fmt::Display> fmt::Display for Json<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl<T: Serialize> Serialize for Json<T> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.0.serialize(serializer) } } /// Creates response with OK status code, correct content type header, and serialized JSON payload. /// /// If serialization failed impl<T: Serialize> Responder for Json<T> { type Body = EitherBody<String>; fn respond_to(self, _: &HttpRequest) -> HttpResponse<Self::Body> { match serde_json::to_string(&self.0) { Ok(body) => match HttpResponse::Ok() .content_type(mime::APPLICATION_JSON) .message_body(body) { Ok(res) => res.map_into_left_body(), Err(err) => HttpResponse::from_error(err).map_into_right_body(), }, Err(err) => { HttpResponse::from_error(JsonPayloadError::Serialize(err)).map_into_right_body() } } } } /// See [here](#extractor) for example of usage as an extractor. impl<T: DeserializeOwned> FromRequest for Json<T> { type Error = Error; type Future = JsonExtractFut<T>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { let config = JsonConfig::from_req(req); let limit = config.limit; let ctype_required = config.content_type_required; let ctype_fn = config.content_type.as_deref(); let err_handler = config.err_handler.clone(); JsonExtractFut { req: Some(req.clone()), fut: JsonBody::new(req, payload, ctype_fn, ctype_required).limit(limit), err_handler, } } } type JsonErrorHandler = Option<Arc<dyn Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync>>; pub struct JsonExtractFut<T> { req: Option<HttpRequest>, fut: JsonBody<T>, err_handler: JsonErrorHandler, } impl<T: DeserializeOwned> Future for JsonExtractFut<T> { type Output = Result<Json<T>, Error>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); let res = ready!(Pin::new(&mut this.fut).poll(cx)); let res = match res { Err(err) => { let req = this.req.take().unwrap(); log::debug!( "Failed to deserialize Json from payload. \ Request path: {}", req.path() ); if let Some(err_handler) = this.err_handler.as_ref() { Err((*err_handler)(err, &req)) } else { Err(err.into()) } } Ok(data) => Ok(Json(data)), }; Poll::Ready(res) } } /// `Json` extractor configuration. /// /// # Examples /// ``` /// use actix_web::{error, post, web, App, FromRequest, HttpResponse}; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Info { /// name: String, /// } /// /// // `Json` extraction is bound by custom `JsonConfig` applied to App. /// #[post("/")] /// async fn index(info: web::Json<Info>) -> String { /// format!("Welcome {}!", info.name) /// } /// /// // custom `Json` extractor configuration /// let json_cfg = web::JsonConfig::default() /// // limit request payload size /// .limit(4096) /// // only accept text/plain content type /// .content_type(|mime| mime == mime::TEXT_PLAIN) /// // use custom error handler /// .error_handler(|err, req| { /// error::InternalError::from_response(err, HttpResponse::Conflict().into()).into() /// }); /// /// App::new() /// .app_data(json_cfg) /// .service(index); /// ``` #[derive(Clone)] pub struct JsonConfig { limit: usize, err_handler: JsonErrorHandler, content_type: Option<Arc<dyn Fn(mime::Mime) -> bool + Send + Sync>>, content_type_required: bool, } impl JsonConfig { /// Set maximum accepted payload size. By default this limit is 2MB. pub fn limit(mut self, limit: usize) -> Self { self.limit = limit; self } /// Set custom error handler. pub fn error_handler<F>(mut self, f: F) -> Self where F: Fn(JsonPayloadError, &HttpRequest) -> Error + Send + Sync + 'static, { self.err_handler = Some(Arc::new(f)); self } /// Set predicate for allowed content types. pub fn content_type<F>(mut self, predicate: F) -> Self where F: Fn(mime::Mime) -> bool + Send + Sync + 'static, { self.content_type = Some(Arc::new(predicate)); self } /// Sets whether or not the request must have a `Content-Type` header to be parsed. pub fn content_type_required(mut self, content_type_required: bool) -> Self { self.content_type_required = content_type_required; self } /// Extract payload config from app data. Check both `T` and `Data<T>`, in that order, and fall /// back to the default payload config. fn from_req(req: &HttpRequest) -> &Self { req.app_data::<Self>() .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref())) .unwrap_or(&DEFAULT_CONFIG) } } const DEFAULT_LIMIT: usize = 2_097_152; // 2 mb /// Allow shared refs used as default. const DEFAULT_CONFIG: JsonConfig = JsonConfig { limit: DEFAULT_LIMIT, err_handler: None, content_type: None, content_type_required: true, }; impl Default for JsonConfig { fn default() -> Self { DEFAULT_CONFIG } } /// Future that resolves to some `T` when parsed from a JSON payload. /// /// Can deserialize any type `T` that implements [`Deserialize`][serde::Deserialize]. /// /// Returns error if: /// - `Content-Type` is not `application/json` when `ctype_required` (passed to [`new`][Self::new]) /// is `true`. /// - `Content-Length` is greater than [limit](JsonBody::limit()). /// - The payload, when consumed, is not valid JSON. pub enum JsonBody<T> { Error(Option<JsonPayloadError>), Body { limit: usize, /// Length as reported by `Content-Length` header, if present. length: Option<usize>, #[cfg(feature = "__compress")] payload: Decompress<Payload>, #[cfg(not(feature = "__compress"))] payload: Payload, buf: BytesMut, _res: PhantomData<T>, }, } impl<T> Unpin for JsonBody<T> {} impl<T: DeserializeOwned> JsonBody<T> { /// Create a new future to decode a JSON request payload. #[allow(clippy::borrow_interior_mutable_const)] pub fn new( req: &HttpRequest, payload: &mut Payload, ctype_fn: Option<&(dyn Fn(mime::Mime) -> bool + Send + Sync)>, ctype_required: bool, ) -> Self { // check content-type let can_parse_json = match (ctype_required, req.mime_type()) { (true, Ok(Some(mime))) => { mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON) || ctype_fn.is_some_and(|predicate| predicate(mime)) } // if content-type is expected but not parsable as mime type, bail (true, _) => false, // if content-type validation is disabled, assume payload is JSON // even when content-type header is missing or invalid mime type (false, _) => true, }; if !can_parse_json { return JsonBody::Error(Some(JsonPayloadError::ContentType)); } let length = ContentLength::parse(req).ok().map(|x| x.0); // Notice the content-length is not checked against limit of json config here. // As the internal usage always call JsonBody::limit after JsonBody::new. // And limit check to return an error variant of JsonBody happens there. let payload = { cfg_if::cfg_if! { if #[cfg(feature = "__compress")] { Decompress::from_headers(payload.take(), req.headers()) } else { payload.take() } } }; JsonBody::Body { limit: DEFAULT_LIMIT, length, payload, buf: BytesMut::with_capacity(8192), _res: PhantomData, } } /// Set maximum accepted payload size. The default limit is 2MB. pub fn limit(self, limit: usize) -> Self { match self { JsonBody::Body { length, payload, buf, .. } => { if let Some(len) = length { if len > limit { return JsonBody::Error(Some(JsonPayloadError::OverflowKnownLength { length: len, limit, })); } } JsonBody::Body { limit, length, payload, buf, _res: PhantomData, } } JsonBody::Error(err) => JsonBody::Error(err), } } } impl<T: DeserializeOwned> Future for JsonBody<T> { type Output = Result<T, JsonPayloadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); match this { JsonBody::Body { limit, buf, payload, .. } => loop { let res = ready!(Pin::new(&mut *payload).poll_next(cx)); match res { Some(chunk) => { let chunk = chunk?; let buf_len = buf.len() + chunk.len(); if buf_len > *limit { return Poll::Ready(Err(JsonPayloadError::Overflow { limit: *limit })); } else { buf.extend_from_slice(&chunk); } } None => { let json = serde_json::from_slice::<T>(buf) .map_err(JsonPayloadError::Deserialize)?; return Poll::Ready(Ok(json)); } } }, JsonBody::Error(err) => Poll::Ready(Err(err.take().unwrap())), } } } #[cfg(test)] mod tests { use bytes::Bytes; use serde::{Deserialize, Serialize}; use super::*; use crate::{ body, error::InternalError, http::{ header::{self, CONTENT_LENGTH, CONTENT_TYPE}, StatusCode, }, test::{assert_body_eq, TestRequest}, }; #[derive(Serialize, Deserialize, PartialEq, Debug)] struct MyObject { name: String, } fn json_eq(err: JsonPayloadError, other: JsonPayloadError) -> bool { match err { JsonPayloadError::Overflow { .. } => { matches!(other, JsonPayloadError::Overflow { .. }) } JsonPayloadError::OverflowKnownLength { .. } => { matches!(other, JsonPayloadError::OverflowKnownLength { .. }) } JsonPayloadError::ContentType => matches!(other, JsonPayloadError::ContentType), _ => false, } } #[actix_rt::test] async fn test_responder() { let req = TestRequest::default().to_http_request(); let j = Json(MyObject { name: "test".to_string(), }); let res = j.respond_to(&req); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(header::CONTENT_TYPE).unwrap(), header::HeaderValue::from_static("application/json") ); assert_body_eq!(res, b"{\"name\":\"test\"}"); } #[actix_rt::test] async fn test_custom_error_responder() { let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data(JsonConfig::default().limit(10).error_handler(|err, _| { let msg = MyObject { name: "invalid request".to_string(), }; let resp = HttpResponse::BadRequest().body(serde_json::to_string(&msg).unwrap()); InternalError::from_response(err, resp).into() })) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; let resp = HttpResponse::from_error(s.unwrap_err()); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let body = body::to_bytes(resp.into_body()).await.unwrap(); let msg: MyObject = serde_json::from_slice(&body).unwrap(); assert_eq!(msg.name, "invalid request"); } #[actix_rt::test] async fn test_extract() { let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await.unwrap(); assert_eq!(s.name, "test"); assert_eq!( s.into_inner(), MyObject { name: "test".to_string() } ); let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data(JsonConfig::default().limit(10)) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; assert!(format!("{}", s.err().unwrap()) .contains("JSON payload (16 bytes) is larger than allowed (limit: 10 bytes).")); let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data( JsonConfig::default() .limit(10) .error_handler(|_, _| JsonPayloadError::ContentType.into()), ) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; assert!(format!("{}", s.err().unwrap()).contains("Content type error")); } #[actix_rt::test] async fn test_json_body() { let (req, mut pl) = TestRequest::default().to_http_parts(); let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await; assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/text"), )) .to_http_parts(); let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await; assert!(json_eq(json.err().unwrap(), JsonPayloadError::ContentType)); let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("10000"), )) .to_http_parts(); let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true) .limit(100) .await; assert!(json_eq( json.err().unwrap(), JsonPayloadError::OverflowKnownLength { length: 10000, limit: 100 } )); let (mut req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .set_payload(Bytes::from_static(&[0u8; 1000])) .to_http_parts(); req.head_mut().headers_mut().remove(header::CONTENT_LENGTH); let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true) .limit(100) .await; assert!(json_eq( json.err().unwrap(), JsonPayloadError::Overflow { limit: 100 } )); let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("application/json"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .to_http_parts(); let json = JsonBody::<MyObject>::new(&req, &mut pl, None, true).await; assert_eq!( json.ok().unwrap(), MyObject { name: "test".to_owned() } ); } #[actix_rt::test] async fn test_with_json_and_bad_content_type() { let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data(JsonConfig::default().limit(4096)) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; assert!(s.is_err()) } #[actix_rt::test] async fn test_with_json_and_good_custom_content_type() { let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("text/plain"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data(JsonConfig::default().content_type(|mime: mime::Mime| { mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN })) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; assert!(s.is_ok()) } #[actix_rt::test] async fn test_with_json_and_bad_custom_content_type() { let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("text/html"), )) .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data(JsonConfig::default().content_type(|mime: mime::Mime| { mime.type_() == mime::TEXT && mime.subtype() == mime::PLAIN })) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; assert!(s.is_err()) } #[actix_rt::test] async fn test_json_with_no_content_type() { let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data(JsonConfig::default().content_type_required(false)) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; assert!(s.is_ok()) } #[actix_rt::test] async fn test_json_ignoring_content_type() { let (req, mut pl) = TestRequest::default() .insert_header(( header::CONTENT_LENGTH, header::HeaderValue::from_static("16"), )) .insert_header(( header::CONTENT_TYPE, header::HeaderValue::from_static("invalid/value"), )) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data(JsonConfig::default().content_type_required(false)) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; assert!(s.is_ok()); } #[actix_rt::test] async fn test_with_config_in_data_wrapper() { let (req, mut pl) = TestRequest::default() .insert_header((CONTENT_TYPE, mime::APPLICATION_JSON)) .insert_header((CONTENT_LENGTH, 16)) .set_payload(Bytes::from_static(b"{\"name\": \"test\"}")) .app_data(web::Data::new(JsonConfig::default().limit(10))) .to_http_parts(); let s = Json::<MyObject>::from_request(&req, &mut pl).await; assert!(s.is_err()); let err_str = s.err().unwrap().to_string(); assert!( err_str.contains("JSON payload (16 bytes) is larger than allowed (limit: 10 bytes).") ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/header.rs
actix-web/src/types/header.rs
//! For header extractor helper documentation, see [`Header`](crate::types::Header). use std::{fmt, ops}; use actix_utils::future::{ready, Ready}; use crate::{ dev::Payload, error::ParseError, extract::FromRequest, http::header::Header as ParseHeader, HttpRequest, }; /// Extract typed headers from the request. /// /// To extract a header, the inner type `T` must implement the /// [`Header`](crate::http::header::Header) trait. /// /// # Examples /// ``` /// use actix_web::{get, web, http::header}; /// /// #[get("/")] /// async fn index(date: web::Header<header::Date>) -> String { /// format!("Request was sent at {}", date.to_string()) /// } /// ``` #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct Header<T>(pub T); impl<T> Header<T> { /// Unwrap into the inner `T` value. pub fn into_inner(self) -> T { self.0 } } impl<T> ops::Deref for Header<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T> ops::DerefMut for Header<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } impl<T> fmt::Display for Header<T> where T: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl<T> FromRequest for Header<T> where T: ParseHeader, { type Error = ParseError; type Future = Ready<Result<Self, Self::Error>>; #[inline] fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { match ParseHeader::parse(req) { Ok(header) => ready(Ok(Header(header))), Err(err) => ready(Err(err)), } } } #[cfg(test)] mod tests { use super::*; use crate::{ http::{header, Method}, test::TestRequest, }; #[actix_rt::test] async fn test_header_extract() { let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .insert_header((header::ALLOW, header::Allow(vec![Method::GET]))) .to_http_parts(); let s = Header::<header::ContentType>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(s.into_inner().0, mime::APPLICATION_JSON); let s = Header::<header::Allow>::from_request(&req, &mut pl) .await .unwrap(); assert_eq!(s.into_inner().0, vec![Method::GET]); assert!(Header::<header::Date>::from_request(&req, &mut pl) .await .is_err()); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/either.rs
actix-web/src/types/either.rs
//! For either helper, see [`Either`]. use std::{ future::Future, mem, pin::Pin, task::{Context, Poll}, }; use bytes::Bytes; use futures_core::ready; use pin_project_lite::pin_project; use crate::{ body::EitherBody, dev, web::{Form, Json}, Error, FromRequest, HttpRequest, HttpResponse, Responder, }; /// Combines two extractor or responder types into a single type. /// /// # Extractor /// Provides a mechanism for trying two extractors, a primary and a fallback. Useful for /// "polymorphic payloads" where, for example, a form might be JSON or URL encoded. /// /// It is important to note that this extractor, by necessity, buffers the entire request payload /// as part of its implementation. Though, it does respect any `PayloadConfig` maximum size limits. /// /// ``` /// use actix_web::{post, web, Either}; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Info { /// name: String, /// } /// /// // handler that accepts form as JSON or form-urlencoded. /// #[post("/")] /// async fn index(form: Either<web::Json<Info>, web::Form<Info>>) -> String { /// let name: String = match form { /// Either::Left(json) => json.name.to_owned(), /// Either::Right(form) => form.name.to_owned(), /// }; /// /// format!("Welcome {}!", name) /// } /// ``` /// /// # Responder /// It may be desirable to use a concrete type for a response with multiple branches. As long as /// both types implement `Responder`, so will the `Either` type, enabling it to be used as a /// handler's return type. /// /// All properties of a response are determined by the Responder branch returned. /// /// ``` /// use actix_web::{get, Either, Error, HttpResponse}; /// /// #[get("/")] /// async fn index() -> Either<&'static str, Result<HttpResponse, Error>> { /// if 1 == 2 { /// // respond with Left variant /// Either::Left("Bad data") /// } else { /// // respond with Right variant /// Either::Right( /// Ok(HttpResponse::Ok() /// .content_type(mime::TEXT_HTML) /// .body("<p>Hello!</p>")) /// ) /// } /// } /// ``` #[derive(Debug, PartialEq, Eq)] pub enum Either<L, R> { /// A value of type `L`. Left(L), /// A value of type `R`. Right(R), } impl<T> Either<Form<T>, Json<T>> { pub fn into_inner(self) -> T { match self { Either::Left(form) => form.into_inner(), Either::Right(form) => form.into_inner(), } } } impl<T> Either<Json<T>, Form<T>> { pub fn into_inner(self) -> T { match self { Either::Left(form) => form.into_inner(), Either::Right(form) => form.into_inner(), } } } #[cfg(test)] impl<L, R> Either<L, R> { pub(self) fn unwrap_left(self) -> L { match self { Either::Left(data) => data, Either::Right(_) => { panic!("Cannot unwrap Left branch. Either contains an `R` type.") } } } pub(self) fn unwrap_right(self) -> R { match self { Either::Left(_) => { panic!("Cannot unwrap Right branch. Either contains an `L` type.") } Either::Right(data) => data, } } } /// See [here](#responder) for example of usage as a handler return type. impl<L, R> Responder for Either<L, R> where L: Responder, R: Responder, { type Body = EitherBody<L::Body, R::Body>; fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body> { match self { Either::Left(a) => a.respond_to(req).map_into_left_body(), Either::Right(b) => b.respond_to(req).map_into_right_body(), } } } /// A composite error resulting from failure to extract an `Either<L, R>`. /// /// The implementation of `Into<actix_web::Error>` will return the payload buffering error or the /// error from the primary extractor. To access the fallback error, use a match clause. #[derive(Debug)] pub enum EitherExtractError<L, R> { /// Error from payload buffering, such as exceeding payload max size limit. Bytes(Error), /// Error from primary and fallback extractors. Extract(L, R), } impl<L, R> From<EitherExtractError<L, R>> for Error where L: Into<Error>, R: Into<Error>, { fn from(err: EitherExtractError<L, R>) -> Error { match err { EitherExtractError::Bytes(err) => err, EitherExtractError::Extract(a_err, _b_err) => a_err.into(), } } } /// See [here](#extractor) for example of usage as an extractor. impl<L, R> FromRequest for Either<L, R> where L: FromRequest + 'static, R: FromRequest + 'static, { type Error = EitherExtractError<L::Error, R::Error>; type Future = EitherExtractFut<L, R>; fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { EitherExtractFut { req: req.clone(), state: EitherExtractState::Bytes { bytes: Bytes::from_request(req, payload), }, } } } pin_project! { pub struct EitherExtractFut<L, R> where R: FromRequest, L: FromRequest, { req: HttpRequest, #[pin] state: EitherExtractState<L, R>, } } pin_project! { #[project = EitherExtractProj] pub enum EitherExtractState<L, R> where L: FromRequest, R: FromRequest, { Bytes { #[pin] bytes: <Bytes as FromRequest>::Future, }, Left { #[pin] left: L::Future, fallback: Bytes, }, Right { #[pin] right: R::Future, left_err: Option<L::Error>, }, } } impl<R, RF, RE, L, LF, LE> Future for EitherExtractFut<L, R> where L: FromRequest<Future = LF, Error = LE>, R: FromRequest<Future = RF, Error = RE>, LF: Future<Output = Result<L, LE>> + 'static, RF: Future<Output = Result<R, RE>> + 'static, LE: Into<Error>, RE: Into<Error>, { type Output = Result<Either<L, R>, EitherExtractError<LE, RE>>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let mut this = self.project(); let ready = loop { let next = match this.state.as_mut().project() { EitherExtractProj::Bytes { bytes } => { let res = ready!(bytes.poll(cx)); match res { Ok(bytes) => { let fallback = bytes.clone(); let left = L::from_request(this.req, &mut dev::Payload::from(bytes)); EitherExtractState::Left { left, fallback } } Err(err) => break Err(EitherExtractError::Bytes(err)), } } EitherExtractProj::Left { left, fallback } => { let res = ready!(left.poll(cx)); match res { Ok(extracted) => break Ok(Either::Left(extracted)), Err(left_err) => { let right = R::from_request( this.req, &mut dev::Payload::from(mem::take(fallback)), ); EitherExtractState::Right { left_err: Some(left_err), right, } } } } EitherExtractProj::Right { right, left_err } => { let res = ready!(right.poll(cx)); match res { Ok(data) => break Ok(Either::Right(data)), Err(err) => { break Err(EitherExtractError::Extract(left_err.take().unwrap(), err)); } } } }; this.state.set(next); }; Poll::Ready(ready) } } #[cfg(test)] mod tests { use serde::{Deserialize, Serialize}; use super::*; use crate::test::TestRequest; #[derive(Debug, Clone, Serialize, Deserialize)] struct TestForm { hello: String, } #[actix_rt::test] async fn test_either_extract_first_try() { let (req, mut pl) = TestRequest::default() .set_form(TestForm { hello: "world".to_owned(), }) .to_http_parts(); let form = Either::<Form<TestForm>, Json<TestForm>>::from_request(&req, &mut pl) .await .unwrap() .unwrap_left() .into_inner(); assert_eq!(&form.hello, "world"); } #[actix_rt::test] async fn test_either_extract_fallback() { let (req, mut pl) = TestRequest::default() .set_json(TestForm { hello: "world".to_owned(), }) .to_http_parts(); let form = Either::<Form<TestForm>, Json<TestForm>>::from_request(&req, &mut pl) .await .unwrap() .unwrap_right() .into_inner(); assert_eq!(&form.hello, "world"); } #[actix_rt::test] async fn test_either_extract_recursive_fallback() { let (req, mut pl) = TestRequest::default() .set_payload(Bytes::from_static(b"!@$%^&*()")) .to_http_parts(); let payload = Either::<Either<Form<TestForm>, Json<TestForm>>, Bytes>::from_request(&req, &mut pl) .await .unwrap() .unwrap_right(); assert_eq!(&payload.as_ref(), &b"!@$%^&*()"); } #[actix_rt::test] async fn test_either_extract_recursive_fallback_inner() { let (req, mut pl) = TestRequest::default() .set_json(TestForm { hello: "world".to_owned(), }) .to_http_parts(); let form = Either::<Either<Form<TestForm>, Json<TestForm>>, Bytes>::from_request(&req, &mut pl) .await .unwrap() .unwrap_left() .unwrap_right() .into_inner(); assert_eq!(&form.hello, "world"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/mod.rs
actix-web/src/types/mod.rs
//! Common extractors and responders. mod either; mod form; mod header; mod html; mod json; mod path; mod payload; mod query; mod readlines; pub use self::{ either::{Either, EitherExtractError}, form::{Form, FormConfig, UrlEncoded}, header::Header, html::Html, json::{Json, JsonBody, JsonConfig}, path::{Path, PathConfig}, payload::{Payload, PayloadConfig}, query::{Query, QueryConfig}, readlines::Readlines, };
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/payload.rs
actix-web/src/types/payload.rs
//! Basic binary and string payload extractors. use std::{ borrow::Cow, future::Future, pin::Pin, str, task::{Context, Poll}, }; use actix_http::error::PayloadError; use actix_utils::future::{ready, Either, Ready}; use bytes::{Bytes, BytesMut}; use encoding_rs::{Encoding, UTF_8}; use futures_core::{ready, stream::Stream}; use mime::Mime; use crate::{ body, dev, error::ErrorBadRequest, http::header, web, Error, FromRequest, HttpMessage, HttpRequest, }; /// Extract a request's raw payload stream. /// /// See [`PayloadConfig`] for important notes when using this advanced extractor. /// /// # Examples /// ``` /// use std::future::Future; /// use futures_util::StreamExt as _; /// use actix_web::{post, web}; /// /// // `body: web::Payload` parameter extracts raw payload stream from request /// #[post("/")] /// async fn index(mut body: web::Payload) -> actix_web::Result<String> { /// // for demonstration only; in a normal case use the `Bytes` extractor /// // collect payload stream into a bytes object /// let mut bytes = web::BytesMut::new(); /// while let Some(item) = body.next().await { /// bytes.extend_from_slice(&item?); /// } /// /// Ok(format!("Request Body Bytes:\n{:?}", bytes)) /// } /// ``` pub struct Payload(dev::Payload); impl Payload { /// Unwrap to inner Payload type. #[inline] pub fn into_inner(self) -> dev::Payload { self.0 } /// Buffers payload from request up to `limit` bytes. /// /// This method is preferred over [`Payload::to_bytes()`] since it will not lead to unexpected /// memory exhaustion from massive payloads. Note that the other primitive extractors such as /// [`Bytes`] and [`String`], as well as extractors built on top of them, already have this sort /// of protection according to the configured (or default) [`PayloadConfig`]. /// /// # Errors /// /// - The outer error type, [`BodyLimitExceeded`](body::BodyLimitExceeded), is returned when the /// payload is larger than `limit`. /// - The inner error type is [the normal Actix Web error](crate::Error) and is only returned if /// the payload stream yields an error for some reason. Such cases are usually caused by /// unrecoverable connection issues. /// /// # Examples /// /// ``` /// use actix_web::{error, web::Payload, Responder}; /// /// async fn limited_payload_handler(pl: Payload) -> actix_web::Result<impl Responder> { /// match pl.to_bytes_limited(5).await { /// Ok(res) => res, /// Err(err) => Err(error::ErrorPayloadTooLarge(err)), /// } /// } /// ``` pub async fn to_bytes_limited( self, limit: usize, ) -> Result<crate::Result<Bytes>, body::BodyLimitExceeded> { let stream = body::BodyStream::new(self.0); match body::to_bytes_limited(stream, limit).await { Ok(Ok(body)) => Ok(Ok(body)), Ok(Err(err)) => Ok(Err(err.into())), Err(err) => Err(err), } } /// Buffers entire payload from request. /// /// Use of this method is discouraged unless you know for certain that requests will not be /// large enough to exhaust memory. If this is not known, prefer [`Payload::to_bytes_limited()`] /// or one of the higher level extractors like [`Bytes`] or [`String`] that implement size /// limits according to the configured (or default) [`PayloadConfig`]. /// /// # Errors /// /// An error is only returned if the payload stream yields an error for some reason. Such cases /// are usually caused by unrecoverable connection issues. /// /// # Examples /// /// ``` /// use actix_web::{error, web::Payload, Responder}; /// /// async fn payload_handler(pl: Payload) -> actix_web::Result<impl Responder> { /// pl.to_bytes().await /// } /// ``` pub async fn to_bytes(self) -> crate::Result<Bytes> { let stream = body::BodyStream::new(self.0); Ok(body::to_bytes(stream).await?) } } impl Stream for Payload { type Item = Result<Bytes, PayloadError>; #[inline] fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { Pin::new(&mut self.0).poll_next(cx) } } /// See [here](#Examples) for example of usage as an extractor. impl FromRequest for Payload { type Error = Error; type Future = Ready<Result<Self, Self::Error>>; #[inline] fn from_request(_: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { ready(Ok(Payload(payload.take()))) } } /// Extract binary data from a request's payload. /// /// Collects request payload stream into a [Bytes] instance. /// /// Use [`PayloadConfig`] to configure extraction process. /// /// # Examples /// ``` /// use actix_web::{post, web}; /// /// /// extract binary data from request /// #[post("/")] /// async fn index(body: web::Bytes) -> String { /// format!("Body {:?}!", body) /// } /// ``` impl FromRequest for Bytes { type Error = Error; type Future = Either<BytesExtractFut, Ready<Result<Bytes, Error>>>; #[inline] fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { // allow both Config and Data<Config> let cfg = PayloadConfig::from_req(req); if let Err(err) = cfg.check_mimetype(req) { return Either::right(ready(Err(err))); } Either::left(BytesExtractFut { body_fut: HttpMessageBody::new(req, payload).limit(cfg.limit), }) } } /// Future for `Bytes` extractor. pub struct BytesExtractFut { body_fut: HttpMessageBody, } impl Future for BytesExtractFut { type Output = Result<Bytes, Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { Pin::new(&mut self.body_fut).poll(cx).map_err(Into::into) } } /// Extract text information from a request's body. /// /// Text extractor automatically decode body according to the request's charset. /// /// Use [`PayloadConfig`] to configure extraction process. /// /// # Examples /// ``` /// use actix_web::{post, web, FromRequest}; /// /// // extract text data from request /// #[post("/")] /// async fn index(text: String) -> String { /// format!("Body {}!", text) /// } impl FromRequest for String { type Error = Error; type Future = Either<StringExtractFut, Ready<Result<String, Error>>>; #[inline] fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { let cfg = PayloadConfig::from_req(req); // check content-type if let Err(err) = cfg.check_mimetype(req) { return Either::right(ready(Err(err))); } // check charset let encoding = match req.encoding() { Ok(enc) => enc, Err(err) => return Either::right(ready(Err(err.into()))), }; let limit = cfg.limit; let body_fut = HttpMessageBody::new(req, payload).limit(limit); Either::left(StringExtractFut { body_fut, encoding }) } } /// Future for `String` extractor. pub struct StringExtractFut { body_fut: HttpMessageBody, encoding: &'static Encoding, } impl Future for StringExtractFut { type Output = Result<String, Error>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let encoding = self.encoding; Pin::new(&mut self.body_fut).poll(cx).map(|out| { let body = out?; bytes_to_string(body, encoding) }) } } fn bytes_to_string(body: Bytes, encoding: &'static Encoding) -> Result<String, Error> { if encoding == UTF_8 { Ok(str::from_utf8(body.as_ref()) .map_err(|_| ErrorBadRequest("Can not decode body"))? .to_owned()) } else { Ok(encoding .decode_without_bom_handling_and_without_replacement(&body) .map(Cow::into_owned) .ok_or_else(|| ErrorBadRequest("Can not decode body"))?) } } /// Configuration for request payloads. /// /// Applies to the built-in [`Bytes`] and [`String`] extractors. /// Note that the [`Payload`] extractor does not automatically check /// conformance with this configuration to allow more flexibility when /// building extractors on top of [`Payload`]. /// /// By default, the payload size limit is 256kB and there is no mime type condition. /// /// To use this, add an instance of it to your [`app`](crate::App), [`scope`](crate::Scope) /// or [`resource`](crate::Resource) through the associated `.app_data()` method. #[derive(Clone)] pub struct PayloadConfig { limit: usize, mimetype: Option<Mime>, } impl PayloadConfig { /// Create new instance with a size limit (in bytes) and no mime type condition. pub fn new(limit: usize) -> Self { Self { limit, ..Default::default() } } /// Set maximum accepted payload size in bytes. The default limit is 256KiB. pub fn limit(mut self, limit: usize) -> Self { self.limit = limit; self } /// Set required mime type of the request. By default mime type is not enforced. pub fn mimetype(mut self, mt: Mime) -> Self { self.mimetype = Some(mt); self } fn check_mimetype(&self, req: &HttpRequest) -> Result<(), Error> { // check content-type if let Some(ref mt) = self.mimetype { match req.mime_type() { Ok(Some(ref req_mt)) => { if mt != req_mt { return Err(ErrorBadRequest("Unexpected Content-Type")); } } Ok(None) => { return Err(ErrorBadRequest("Content-Type is expected")); } Err(err) => { return Err(err.into()); } } } Ok(()) } /// Extract payload config from app data. Check both `T` and `Data<T>`, in that order, and fall /// back to the default payload config if neither is found. fn from_req(req: &HttpRequest) -> &Self { req.app_data::<Self>() .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref())) .unwrap_or(&DEFAULT_CONFIG) } } const DEFAULT_CONFIG_LIMIT: usize = 262_144; // 2^18 bytes (~256kB) /// Allow shared refs used as defaults. const DEFAULT_CONFIG: PayloadConfig = PayloadConfig { limit: DEFAULT_CONFIG_LIMIT, mimetype: None, }; impl Default for PayloadConfig { fn default() -> Self { DEFAULT_CONFIG } } /// Future that resolves to a complete HTTP body payload. /// /// By default only 256kB payload is accepted before `PayloadError::Overflow` is returned. /// Use `MessageBody::limit()` method to change upper limit. pub struct HttpMessageBody { limit: usize, length: Option<usize>, #[cfg(feature = "__compress")] stream: dev::Decompress<dev::Payload>, #[cfg(not(feature = "__compress"))] stream: dev::Payload, buf: BytesMut, err: Option<PayloadError>, } impl HttpMessageBody { /// Create `MessageBody` for request. #[allow(clippy::borrow_interior_mutable_const)] pub fn new(req: &HttpRequest, payload: &mut dev::Payload) -> HttpMessageBody { let mut length = None; let mut err = None; if let Some(l) = req.headers().get(&header::CONTENT_LENGTH) { match l.to_str() { Ok(s) => match s.parse::<usize>() { Ok(l) => { if l > DEFAULT_CONFIG_LIMIT { err = Some(PayloadError::Overflow); } length = Some(l) } Err(_) => err = Some(PayloadError::UnknownLength), }, Err(_) => err = Some(PayloadError::UnknownLength), } } let stream = { cfg_if::cfg_if! { if #[cfg(feature = "__compress")] { dev::Decompress::from_headers(payload.take(), req.headers()) } else { payload.take() } } }; HttpMessageBody { stream, limit: DEFAULT_CONFIG_LIMIT, length, buf: BytesMut::with_capacity(8192), err, } } /// Change max size of payload. By default max size is 256kB pub fn limit(mut self, limit: usize) -> Self { if let Some(l) = self.length { self.err = if l > limit { Some(PayloadError::Overflow) } else { None }; } self.limit = limit; self } } impl Future for HttpMessageBody { type Output = Result<Bytes, PayloadError>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let this = self.get_mut(); if let Some(err) = this.err.take() { return Poll::Ready(Err(err)); } loop { let res = ready!(Pin::new(&mut this.stream).poll_next(cx)); match res { Some(chunk) => { let chunk = chunk?; if this.buf.len() + chunk.len() > this.limit { return Poll::Ready(Err(PayloadError::Overflow)); } else { this.buf.extend_from_slice(&chunk); } } None => return Poll::Ready(Ok(this.buf.split().freeze())), } } } } #[cfg(test)] mod tests { use super::*; use crate::{ http::StatusCode, test::{call_service, init_service, read_body, TestRequest}, App, Responder, }; #[actix_rt::test] async fn payload_to_bytes() { async fn payload_handler(pl: Payload) -> crate::Result<impl Responder> { pl.to_bytes().await } async fn limited_payload_handler(pl: Payload) -> crate::Result<impl Responder> { match pl.to_bytes_limited(5).await { Ok(res) => res, Err(_limited) => Err(ErrorBadRequest("too big")), } } let srv = init_service( App::new() .route("/all", web::to(payload_handler)) .route("limited", web::to(limited_payload_handler)), ) .await; let req = TestRequest::with_uri("/all") .set_payload("1234567890") .to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let body = read_body(res).await; assert_eq!(body, "1234567890"); let req = TestRequest::with_uri("/limited") .set_payload("1234567890") .to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/limited") .set_payload("12345") .to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let body = read_body(res).await; assert_eq!(body, "12345"); } #[actix_rt::test] async fn test_payload_config() { let req = TestRequest::default().to_http_request(); let cfg = PayloadConfig::default().mimetype(mime::APPLICATION_JSON); assert!(cfg.check_mimetype(&req).is_err()); let req = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/x-www-form-urlencoded")) .to_http_request(); assert!(cfg.check_mimetype(&req).is_err()); let req = TestRequest::default() .insert_header((header::CONTENT_TYPE, "application/json")) .to_http_request(); assert!(cfg.check_mimetype(&req).is_ok()); } // allow deprecated App::data #[allow(deprecated)] #[actix_rt::test] async fn test_config_recall_locations() { async fn bytes_handler(_: Bytes) -> impl Responder { "payload is probably json bytes" } async fn string_handler(_: String) -> impl Responder { "payload is probably json string" } let srv = init_service( App::new() .service( web::resource("/bytes-app-data") .app_data(PayloadConfig::default().mimetype(mime::APPLICATION_JSON)) .route(web::get().to(bytes_handler)), ) .service( web::resource("/bytes-data") .data(PayloadConfig::default().mimetype(mime::APPLICATION_JSON)) .route(web::get().to(bytes_handler)), ) .service( web::resource("/string-app-data") .app_data(PayloadConfig::default().mimetype(mime::APPLICATION_JSON)) .route(web::get().to(string_handler)), ) .service( web::resource("/string-data") .data(PayloadConfig::default().mimetype(mime::APPLICATION_JSON)) .route(web::get().to(string_handler)), ), ) .await; let req = TestRequest::with_uri("/bytes-app-data").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/bytes-data").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/string-app-data").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/string-data").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); let req = TestRequest::with_uri("/bytes-app-data") .insert_header(header::ContentType(mime::APPLICATION_JSON)) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/bytes-data") .insert_header(header::ContentType(mime::APPLICATION_JSON)) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/string-app-data") .insert_header(header::ContentType(mime::APPLICATION_JSON)) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let req = TestRequest::with_uri("/string-data") .insert_header(header::ContentType(mime::APPLICATION_JSON)) .to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_bytes() { let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_LENGTH, "11")) .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); let s = Bytes::from_request(&req, &mut pl).await.unwrap(); assert_eq!(s, Bytes::from_static(b"hello=world")); } #[actix_rt::test] async fn test_string() { let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_LENGTH, "11")) .set_payload(Bytes::from_static(b"hello=world")) .to_http_parts(); let s = String::from_request(&req, &mut pl).await.unwrap(); assert_eq!(s, "hello=world"); } #[actix_rt::test] async fn test_message_body() { let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_LENGTH, "xxxx")) .to_srv_request() .into_parts(); let res = HttpMessageBody::new(&req, &mut pl).await; match res.err().unwrap() { PayloadError::UnknownLength => {} _ => unreachable!("error"), } let (req, mut pl) = TestRequest::default() .insert_header((header::CONTENT_LENGTH, "1000000")) .to_srv_request() .into_parts(); let res = HttpMessageBody::new(&req, &mut pl).await; match res.err().unwrap() { PayloadError::Overflow => {} _ => unreachable!("error"), } let (req, mut pl) = TestRequest::default() .set_payload(Bytes::from_static(b"test")) .to_http_parts(); let res = HttpMessageBody::new(&req, &mut pl).await; assert_eq!(res.ok().unwrap(), Bytes::from_static(b"test")); let (req, mut pl) = TestRequest::default() .set_payload(Bytes::from_static(b"11111111111111")) .to_http_parts(); let res = HttpMessageBody::new(&req, &mut pl).limit(5).await; match res.err().unwrap() { PayloadError::Overflow => {} _ => unreachable!("error"), } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/readlines.rs
actix-web/src/types/readlines.rs
//! For request line reader documentation, see [`Readlines`]. use std::{ borrow::Cow, pin::Pin, str, task::{Context, Poll}, }; use bytes::{Bytes, BytesMut}; use encoding_rs::{Encoding, UTF_8}; use futures_core::{ready, stream::Stream}; use crate::{ dev::Payload, error::{PayloadError, ReadlinesError}, HttpMessage, }; /// Stream that reads request line by line. pub struct Readlines<T: HttpMessage> { stream: Payload<T::Stream>, buf: BytesMut, limit: usize, checked_buff: bool, encoding: &'static Encoding, err: Option<ReadlinesError>, } impl<T> Readlines<T> where T: HttpMessage, T::Stream: Stream<Item = Result<Bytes, PayloadError>> + Unpin, { /// Create a new stream to read request line by line. pub fn new(req: &mut T) -> Self { let encoding = match req.encoding() { Ok(enc) => enc, Err(err) => return Self::err(err.into()), }; Readlines { stream: req.take_payload(), buf: BytesMut::with_capacity(262_144), limit: 262_144, checked_buff: true, err: None, encoding, } } /// Set maximum accepted payload size. The default limit is 256kB. pub fn limit(mut self, limit: usize) -> Self { self.limit = limit; self } fn err(err: ReadlinesError) -> Self { Readlines { stream: Payload::None, buf: BytesMut::new(), limit: 262_144, checked_buff: true, encoding: UTF_8, err: Some(err), } } } impl<T> Stream for Readlines<T> where T: HttpMessage, T::Stream: Stream<Item = Result<Bytes, PayloadError>> + Unpin, { type Item = Result<String, ReadlinesError>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.get_mut(); if let Some(err) = this.err.take() { return Poll::Ready(Some(Err(err))); } // check if there is a newline in the buffer if !this.checked_buff { let mut found: Option<usize> = None; for (ind, b) in this.buf.iter().enumerate() { if *b == b'\n' { found = Some(ind); break; } } if let Some(ind) = found { // check if line is longer than limit if ind + 1 > this.limit { return Poll::Ready(Some(Err(ReadlinesError::LimitOverflow))); } let line = if this.encoding == UTF_8 { str::from_utf8(&this.buf.split_to(ind + 1)) .map_err(|_| ReadlinesError::EncodingError)? .to_owned() } else { this.encoding .decode_without_bom_handling_and_without_replacement( &this.buf.split_to(ind + 1), ) .map(Cow::into_owned) .ok_or(ReadlinesError::EncodingError)? }; return Poll::Ready(Some(Ok(line))); } this.checked_buff = true; } // poll req for more bytes match ready!(Pin::new(&mut this.stream).poll_next(cx)) { Some(Ok(mut bytes)) => { // check if there is a newline in bytes let mut found: Option<usize> = None; for (ind, b) in bytes.iter().enumerate() { if *b == b'\n' { found = Some(ind); break; } } if let Some(ind) = found { // check if line is longer than limit if ind + 1 > this.limit { return Poll::Ready(Some(Err(ReadlinesError::LimitOverflow))); } let line = if this.encoding == UTF_8 { str::from_utf8(&bytes.split_to(ind + 1)) .map_err(|_| ReadlinesError::EncodingError)? .to_owned() } else { this.encoding .decode_without_bom_handling_and_without_replacement( &bytes.split_to(ind + 1), ) .map(Cow::into_owned) .ok_or(ReadlinesError::EncodingError)? }; // extend buffer with rest of the bytes; this.buf.extend_from_slice(&bytes); this.checked_buff = false; return Poll::Ready(Some(Ok(line))); } this.buf.extend_from_slice(&bytes); Poll::Pending } None => { if this.buf.is_empty() { return Poll::Ready(None); } if this.buf.len() > this.limit { return Poll::Ready(Some(Err(ReadlinesError::LimitOverflow))); } let line = if this.encoding == UTF_8 { str::from_utf8(&this.buf) .map_err(|_| ReadlinesError::EncodingError)? .to_owned() } else { this.encoding .decode_without_bom_handling_and_without_replacement(&this.buf) .map(Cow::into_owned) .ok_or(ReadlinesError::EncodingError)? }; this.buf.clear(); Poll::Ready(Some(Ok(line))) } Some(Err(err)) => Poll::Ready(Some(Err(ReadlinesError::from(err)))), } } } #[cfg(test)] mod tests { use futures_util::StreamExt as _; use super::*; use crate::test::TestRequest; #[actix_rt::test] async fn test_readlines() { let mut req = TestRequest::default() .set_payload(Bytes::from_static( b"Lorem Ipsum is simply dummy text of the printing and typesetting\n\ industry. Lorem Ipsum has been the industry's standard dummy\n\ Contrary to popular belief, Lorem Ipsum is not simply random text.", )) .to_request(); let mut stream = Readlines::new(&mut req); assert_eq!( stream.next().await.unwrap().unwrap(), "Lorem Ipsum is simply dummy text of the printing and typesetting\n" ); assert_eq!( stream.next().await.unwrap().unwrap(), "industry. Lorem Ipsum has been the industry's standard dummy\n" ); assert_eq!( stream.next().await.unwrap().unwrap(), "Contrary to popular belief, Lorem Ipsum is not simply random text." ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/types/query.rs
actix-web/src/types/query.rs
//! For query parameter extractor documentation, see [`Query`]. use std::{fmt, ops, sync::Arc}; use actix_utils::future::{ok, ready, Ready}; use serde::de::DeserializeOwned; use crate::{dev::Payload, error::QueryPayloadError, Error, FromRequest, HttpRequest}; /// Extract typed information from the request's query. /// /// To extract typed data from the URL query string, the inner type `T` must implement the /// [`DeserializeOwned`] trait. /// /// Use [`QueryConfig`] to configure extraction process. /// /// # Panics /// A query string consists of unordered `key=value` pairs, therefore it cannot be decoded into any /// type which depends upon data ordering (eg. tuples). Trying to do so will result in a panic. /// /// # Examples /// ``` /// use actix_web::{get, web}; /// use serde::Deserialize; /// /// #[derive(Debug, Deserialize)] /// pub enum ResponseType { /// Token, /// Code /// } /// /// #[derive(Debug, Deserialize)] /// pub struct AuthRequest { /// id: u64, /// response_type: ResponseType, /// } /// /// // Deserialize `AuthRequest` struct from query string. /// // This handler gets called only if the request's query parameters contain both fields. /// // A valid request path for this handler would be `/?id=64&response_type=Code"`. /// #[get("/")] /// async fn index(info: web::Query<AuthRequest>) -> String { /// format!("Authorization request for id={} and type={:?}!", info.id, info.response_type) /// } /// /// // To access the entire underlying query struct, use `.into_inner()`. /// #[get("/debug1")] /// async fn debug1(info: web::Query<AuthRequest>) -> String { /// dbg!("Authorization object = {:?}", info.into_inner()); /// "OK".to_string() /// } /// /// // Or use destructuring, which is equivalent to `.into_inner()`. /// #[get("/debug2")] /// async fn debug2(web::Query(info): web::Query<AuthRequest>) -> String { /// dbg!("Authorization object = {:?}", info); /// "OK".to_string() /// } /// ``` #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Query<T>(pub T); impl<T> Query<T> { /// Unwrap into inner `T` value. pub fn into_inner(self) -> T { self.0 } } impl<T: DeserializeOwned> Query<T> { /// Deserialize a `T` from the URL encoded query parameter string. /// /// ``` /// # use std::collections::HashMap; /// # use actix_web::web::Query; /// let numbers = Query::<HashMap<String, u32>>::from_query("one=1&two=2").unwrap(); /// assert_eq!(numbers.get("one"), Some(&1)); /// assert_eq!(numbers.get("two"), Some(&2)); /// assert!(numbers.get("three").is_none()); /// ``` pub fn from_query(query_str: &str) -> Result<Self, QueryPayloadError> { serde_urlencoded::from_str::<T>(query_str) .map(Self) .map_err(QueryPayloadError::Deserialize) } } impl<T> ops::Deref for Query<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T> ops::DerefMut for Query<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } impl<T: fmt::Display> fmt::Display for Query<T> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.0.fmt(f) } } /// See [here](#Examples) for example of usage as an extractor. impl<T: DeserializeOwned> FromRequest for Query<T> { type Error = Error; type Future = Ready<Result<Self, Error>>; #[inline] fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { let error_handler = req .app_data::<QueryConfig>() .and_then(|c| c.err_handler.clone()); serde_urlencoded::from_str::<T>(req.query_string()) .map(|val| ok(Query(val))) .unwrap_or_else(move |err| { let err = QueryPayloadError::Deserialize(err); log::debug!( "Failed during Query extractor deserialization. \ Request path: {:?}", req.path() ); let err = if let Some(error_handler) = error_handler { (error_handler)(err, req) } else { err.into() }; ready(Err(err)) }) } } /// Query extractor configuration. /// /// # Examples /// ``` /// use actix_web::{error, get, web, App, FromRequest, HttpResponse}; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Info { /// username: String, /// } /// /// /// deserialize `Info` from request's querystring /// #[get("/")] /// async fn index(info: web::Query<Info>) -> String { /// format!("Welcome {}!", info.username) /// } /// /// // custom `Query` extractor configuration /// let query_cfg = web::QueryConfig::default() /// // use custom error handler /// .error_handler(|err, req| { /// error::InternalError::from_response(err, HttpResponse::Conflict().finish()).into() /// }); /// /// App::new() /// .app_data(query_cfg) /// .service(index); /// ``` #[derive(Clone, Default)] pub struct QueryConfig { #[allow(clippy::type_complexity)] err_handler: Option<Arc<dyn Fn(QueryPayloadError, &HttpRequest) -> Error + Send + Sync>>, } impl QueryConfig { /// Set custom error handler pub fn error_handler<F>(mut self, f: F) -> Self where F: Fn(QueryPayloadError, &HttpRequest) -> Error + Send + Sync + 'static, { self.err_handler = Some(Arc::new(f)); self } } #[cfg(test)] mod tests { use actix_http::StatusCode; use derive_more::Display; use serde::Deserialize; use super::*; use crate::{error::InternalError, test::TestRequest, HttpResponse}; #[derive(Deserialize, Debug, Display)] struct Id { id: String, } #[actix_rt::test] async fn test_service_request_extract() { let req = TestRequest::with_uri("/name/user1/").to_srv_request(); assert!(Query::<Id>::from_query(req.query_string()).is_err()); let req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request(); let mut s = Query::<Id>::from_query(req.query_string()).unwrap(); assert_eq!(s.id, "test"); assert_eq!( format!("{}, {:?}", s, s), "test, Query(Id { id: \"test\" })" ); s.id = "test1".to_string(); let s = s.into_inner(); assert_eq!(s.id, "test1"); } #[actix_rt::test] async fn test_request_extract() { let req = TestRequest::with_uri("/name/user1/").to_srv_request(); let (req, mut pl) = req.into_parts(); assert!(Query::<Id>::from_request(&req, &mut pl).await.is_err()); let req = TestRequest::with_uri("/name/user1/?id=test").to_srv_request(); let (req, mut pl) = req.into_parts(); let mut s = Query::<Id>::from_request(&req, &mut pl).await.unwrap(); assert_eq!(s.id, "test"); assert_eq!( format!("{}, {:?}", s, s), "test, Query(Id { id: \"test\" })" ); s.id = "test1".to_string(); let s = s.into_inner(); assert_eq!(s.id, "test1"); } #[actix_rt::test] #[should_panic] async fn test_tuple_panic() { let req = TestRequest::with_uri("/?one=1&two=2").to_srv_request(); let (req, mut pl) = req.into_parts(); Query::<(u32, u32)>::from_request(&req, &mut pl) .await .unwrap(); } #[actix_rt::test] async fn test_custom_error_responder() { let req = TestRequest::with_uri("/name/user1/") .app_data(QueryConfig::default().error_handler(|e, _| { let resp = HttpResponse::UnprocessableEntity().finish(); InternalError::from_response(e, resp).into() })) .to_srv_request(); let (req, mut pl) = req.into_parts(); let query = Query::<Id>::from_request(&req, &mut pl).await; assert!(query.is_err()); assert_eq!( query .unwrap_err() .as_response_error() .error_response() .status(), StatusCode::UNPROCESSABLE_ENTITY ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/guard/acceptable.rs
actix-web/src/guard/acceptable.rs
use super::{Guard, GuardContext}; use crate::http::header::Accept; /// A guard that verifies that an `Accept` header is present and it contains a compatible MIME type. /// /// An exception is that matching `*/*` must be explicitly enabled because most browsers send this /// as part of their `Accept` header for almost every request. /// /// # Examples /// ``` /// use actix_web::{guard::Acceptable, web, HttpResponse}; /// /// web::resource("/images") /// .guard(Acceptable::new(mime::IMAGE_STAR)) /// .default_service(web::to(|| async { /// HttpResponse::Ok().body("only called when images responses are acceptable") /// })); /// ``` #[derive(Debug, Clone)] pub struct Acceptable { mime: mime::Mime, /// Whether to match `*/*` mime type. /// /// Defaults to false because it's not very useful otherwise. match_star_star: bool, } impl Acceptable { /// Constructs new `Acceptable` guard with the given `mime` type/pattern. pub fn new(mime: mime::Mime) -> Self { Self { mime, match_star_star: false, } } /// Allows `*/*` in the `Accept` header to pass the guard check. pub fn match_star_star(mut self) -> Self { self.match_star_star = true; self } } impl Guard for Acceptable { fn check(&self, ctx: &GuardContext<'_>) -> bool { let accept = match ctx.header::<Accept>() { Some(hdr) => hdr, None => return false, }; let target_type = self.mime.type_(); let target_subtype = self.mime.subtype(); for mime in accept.0.into_iter().map(|q| q.item) { return match (mime.type_(), mime.subtype()) { (typ, subtype) if typ == target_type && subtype == target_subtype => true, (typ, mime::STAR) if typ == target_type => true, (mime::STAR, mime::STAR) if self.match_star_star => true, _ => continue, }; } false } } #[cfg(test)] mod tests { use super::*; use crate::{http::header, test::TestRequest}; #[test] fn test_acceptable() { let req = TestRequest::default().to_srv_request(); assert!(!Acceptable::new(mime::APPLICATION_JSON).check(&req.guard_ctx())); let req = TestRequest::default() .insert_header((header::ACCEPT, "application/json")) .to_srv_request(); assert!(Acceptable::new(mime::APPLICATION_JSON).check(&req.guard_ctx())); let req = TestRequest::default() .insert_header((header::ACCEPT, "text/html, application/json")) .to_srv_request(); assert!(Acceptable::new(mime::APPLICATION_JSON).check(&req.guard_ctx())); } #[test] fn test_acceptable_star() { let req = TestRequest::default() .insert_header((header::ACCEPT, "text/html, */*;q=0.8")) .to_srv_request(); assert!(Acceptable::new(mime::APPLICATION_JSON) .match_star_star() .check(&req.guard_ctx())); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/guard/mod.rs
actix-web/src/guard/mod.rs
//! Route guards. //! //! Guards are used during routing to help select a matching service or handler using some aspect of //! the request; though guards should not be used for path matching since it is a built-in function //! of the Actix Web router. //! //! Guards can be used on [`Scope`]s, [`Resource`]s, [`Route`]s, and other custom services. //! //! Fundamentally, a guard is a predicate function that receives a reference to a request context //! object and returns a boolean; true if the request _should_ be handled by the guarded service //! or handler. This interface is defined by the [`Guard`] trait. //! //! Commonly-used guards are provided in this module as well as a way of creating a guard from a //! closure ([`fn_guard`]). The [`Not`], [`Any`], and [`All`] guards are noteworthy, as they can be //! used to compose other guards in a more flexible and semantic way than calling `.guard(...)` on //! services multiple times (which might have different combining behavior than you want). //! //! There are shortcuts for routes with method guards in the [`web`](crate::web) module: //! [`web::get()`](crate::web::get), [`web::post()`](crate::web::post), etc. The routes created by //! the following calls are equivalent: //! //! - `web::get()` (recommended form) //! - `web::route().guard(guard::Get())` //! //! Guards can not modify anything about the request. However, it is possible to store extra //! attributes in the request-local data container obtained with [`GuardContext::req_data_mut`]. //! //! Guards can prevent resource definitions from overlapping which, when only considering paths, //! would result in inaccessible routes. See the [`Host`] guard for an example of virtual hosting. //! //! # Examples //! //! In the following code, the `/guarded` resource has one defined route whose handler will only be //! called if the request method is GET or POST and there is a `x-guarded` request header with value //! equal to `secret`. //! //! ``` //! use actix_web::{web, http::Method, guard, HttpResponse}; //! //! web::resource("/guarded").route( //! web::route() //! .guard(guard::Any(guard::Get()).or(guard::Post())) //! .guard(guard::Header("x-guarded", "secret")) //! .to(|| HttpResponse::Ok()) //! ); //! ``` //! //! [`Scope`]: crate::Scope::guard() //! [`Resource`]: crate::Resource::guard() //! [`Route`]: crate::Route::guard() use std::{ cell::{Ref, RefMut}, rc::Rc, }; use actix_http::{header, Extensions, Method as HttpMethod, RequestHead}; use crate::{http::header::Header, service::ServiceRequest, HttpMessage as _}; mod acceptable; mod host; pub use self::{ acceptable::Acceptable, host::{Host, HostGuard}, }; /// Provides access to request parts that are useful during routing. #[derive(Debug)] pub struct GuardContext<'a> { pub(crate) req: &'a ServiceRequest, } impl<'a> GuardContext<'a> { /// Returns reference to the request head. #[inline] pub fn head(&self) -> &RequestHead { self.req.head() } /// Returns reference to the request-local data/extensions container. #[inline] pub fn req_data(&self) -> Ref<'a, Extensions> { self.req.extensions() } /// Returns mutable reference to the request-local data/extensions container. #[inline] pub fn req_data_mut(&self) -> RefMut<'a, Extensions> { self.req.extensions_mut() } /// Extracts a typed header from the request. /// /// Returns `None` if parsing `H` fails. /// /// # Examples /// ``` /// use actix_web::{guard::fn_guard, http::header}; /// /// let image_accept_guard = fn_guard(|ctx| { /// match ctx.header::<header::Accept>() { /// Some(hdr) => hdr.preference() == "image/*", /// None => false, /// } /// }); /// ``` #[inline] pub fn header<H: Header>(&self) -> Option<H> { H::parse(self.req).ok() } /// Counterpart to [HttpRequest::app_data](crate::HttpRequest::app_data). #[inline] pub fn app_data<T: 'static>(&self) -> Option<&T> { self.req.app_data() } } /// Interface for routing guards. /// /// See [module level documentation](self) for more. pub trait Guard { /// Returns true if predicate condition is met for a given request. fn check(&self, ctx: &GuardContext<'_>) -> bool; } impl Guard for Rc<dyn Guard> { fn check(&self, ctx: &GuardContext<'_>) -> bool { (**self).check(ctx) } } /// Creates a guard using the given function. /// /// # Examples /// ``` /// use actix_web::{guard, web, HttpResponse}; /// /// web::route() /// .guard(guard::fn_guard(|ctx| { /// ctx.head().headers().contains_key("content-type") /// })) /// .to(|| HttpResponse::Ok()); /// ``` pub fn fn_guard<F>(f: F) -> impl Guard where F: Fn(&GuardContext<'_>) -> bool, { FnGuard(f) } struct FnGuard<F: Fn(&GuardContext<'_>) -> bool>(F); impl<F> Guard for FnGuard<F> where F: Fn(&GuardContext<'_>) -> bool, { fn check(&self, ctx: &GuardContext<'_>) -> bool { (self.0)(ctx) } } impl<F> Guard for F where F: Fn(&GuardContext<'_>) -> bool, { fn check(&self, ctx: &GuardContext<'_>) -> bool { (self)(ctx) } } /// Creates a guard that matches if any added guards match. /// /// # Examples /// The handler below will be called for either request method `GET` or `POST`. /// ``` /// use actix_web::{web, guard, HttpResponse}; /// /// web::route() /// .guard( /// guard::Any(guard::Get()) /// .or(guard::Post())) /// .to(|| HttpResponse::Ok()); /// ``` #[allow(non_snake_case)] pub fn Any<F: Guard + 'static>(guard: F) -> AnyGuard { AnyGuard { guards: vec![Box::new(guard)], } } /// A collection of guards that match if the disjunction of their `check` outcomes is true. /// /// That is, only one contained guard needs to match in order for the aggregate guard to match. /// /// Construct an `AnyGuard` using [`Any`]. pub struct AnyGuard { guards: Vec<Box<dyn Guard>>, } impl AnyGuard { /// Adds new guard to the collection of guards to check. pub fn or<F: Guard + 'static>(mut self, guard: F) -> Self { self.guards.push(Box::new(guard)); self } } impl Guard for AnyGuard { #[inline] fn check(&self, ctx: &GuardContext<'_>) -> bool { for guard in &self.guards { if guard.check(ctx) { return true; } } false } } /// Creates a guard that matches if all added guards match. /// /// # Examples /// The handler below will only be called if the request method is `GET` **and** the specified /// header name and value match exactly. /// ``` /// use actix_web::{guard, web, HttpResponse}; /// /// web::route() /// .guard( /// guard::All(guard::Get()) /// .and(guard::Header("accept", "text/plain")) /// ) /// .to(|| HttpResponse::Ok()); /// ``` #[allow(non_snake_case)] pub fn All<F: Guard + 'static>(guard: F) -> AllGuard { AllGuard { guards: vec![Box::new(guard)], } } /// A collection of guards that match if the conjunction of their `check` outcomes is true. /// /// That is, **all** contained guard needs to match in order for the aggregate guard to match. /// /// Construct an `AllGuard` using [`All`]. pub struct AllGuard { guards: Vec<Box<dyn Guard>>, } impl AllGuard { /// Adds new guard to the collection of guards to check. pub fn and<F: Guard + 'static>(mut self, guard: F) -> Self { self.guards.push(Box::new(guard)); self } } impl Guard for AllGuard { #[inline] fn check(&self, ctx: &GuardContext<'_>) -> bool { for guard in &self.guards { if !guard.check(ctx) { return false; } } true } } /// Wraps a guard and inverts the outcome of its `Guard` implementation. /// /// # Examples /// The handler below will be called for any request method apart from `GET`. /// ``` /// use actix_web::{guard, web, HttpResponse}; /// /// web::route() /// .guard(guard::Not(guard::Get())) /// .to(|| HttpResponse::Ok()); /// ``` pub struct Not<G>(pub G); impl<G: Guard> Guard for Not<G> { #[inline] fn check(&self, ctx: &GuardContext<'_>) -> bool { !self.0.check(ctx) } } /// Creates a guard that matches a specified HTTP method. #[allow(non_snake_case)] pub fn Method(method: HttpMethod) -> impl Guard { MethodGuard(method) } #[derive(Debug, Clone)] pub(crate) struct RegisteredMethods(pub(crate) Vec<HttpMethod>); /// HTTP method guard. #[derive(Debug)] pub(crate) struct MethodGuard(HttpMethod); impl Guard for MethodGuard { fn check(&self, ctx: &GuardContext<'_>) -> bool { let registered = ctx.req_data_mut().remove::<RegisteredMethods>(); if let Some(mut methods) = registered { methods.0.push(self.0.clone()); ctx.req_data_mut().insert(methods); } else { ctx.req_data_mut() .insert(RegisteredMethods(vec![self.0.clone()])); } ctx.head().method == self.0 } } macro_rules! method_guard { ($method_fn:ident, $method_const:ident) => { #[doc = concat!("Creates a guard that matches the `", stringify!($method_const), "` request method.")] /// /// # Examples #[doc = concat!("The route in this example will only respond to `", stringify!($method_const), "` requests.")] /// ``` /// use actix_web::{guard, web, HttpResponse}; /// /// web::route() #[doc = concat!(" .guard(guard::", stringify!($method_fn), "())")] /// .to(|| HttpResponse::Ok()); /// ``` #[allow(non_snake_case)] pub fn $method_fn() -> impl Guard { MethodGuard(HttpMethod::$method_const) } }; } method_guard!(Get, GET); method_guard!(Post, POST); method_guard!(Put, PUT); method_guard!(Delete, DELETE); method_guard!(Head, HEAD); method_guard!(Options, OPTIONS); method_guard!(Connect, CONNECT); method_guard!(Patch, PATCH); method_guard!(Trace, TRACE); /// Creates a guard that matches if request contains given header name and value. /// /// # Examples /// The handler below will be called when the request contains an `x-guarded` header with value /// equal to `secret`. /// ``` /// use actix_web::{guard, web, HttpResponse}; /// /// web::route() /// .guard(guard::Header("x-guarded", "secret")) /// .to(|| HttpResponse::Ok()); /// ``` #[allow(non_snake_case)] pub fn Header(name: &'static str, value: &'static str) -> impl Guard { HeaderGuard( header::HeaderName::try_from(name).unwrap(), header::HeaderValue::from_static(value), ) } struct HeaderGuard(header::HeaderName, header::HeaderValue); impl Guard for HeaderGuard { fn check(&self, ctx: &GuardContext<'_>) -> bool { if let Some(val) = ctx.head().headers.get(&self.0) { return val == self.1; } false } } #[cfg(test)] mod tests { use actix_http::Method; use super::*; use crate::test::TestRequest; #[test] fn header_match() { let req = TestRequest::default() .insert_header((header::TRANSFER_ENCODING, "chunked")) .to_srv_request(); let hdr = Header("transfer-encoding", "chunked"); assert!(hdr.check(&req.guard_ctx())); let hdr = Header("transfer-encoding", "other"); assert!(!hdr.check(&req.guard_ctx())); let hdr = Header("content-type", "chunked"); assert!(!hdr.check(&req.guard_ctx())); let hdr = Header("content-type", "other"); assert!(!hdr.check(&req.guard_ctx())); } #[test] fn method_guards() { let get_req = TestRequest::get().to_srv_request(); let post_req = TestRequest::post().to_srv_request(); assert!(Get().check(&get_req.guard_ctx())); assert!(!Get().check(&post_req.guard_ctx())); assert!(Post().check(&post_req.guard_ctx())); assert!(!Post().check(&get_req.guard_ctx())); let req = TestRequest::put().to_srv_request(); assert!(Put().check(&req.guard_ctx())); assert!(!Put().check(&get_req.guard_ctx())); let req = TestRequest::patch().to_srv_request(); assert!(Patch().check(&req.guard_ctx())); assert!(!Patch().check(&get_req.guard_ctx())); let r = TestRequest::delete().to_srv_request(); assert!(Delete().check(&r.guard_ctx())); assert!(!Delete().check(&get_req.guard_ctx())); let req = TestRequest::default().method(Method::HEAD).to_srv_request(); assert!(Head().check(&req.guard_ctx())); assert!(!Head().check(&get_req.guard_ctx())); let req = TestRequest::default() .method(Method::OPTIONS) .to_srv_request(); assert!(Options().check(&req.guard_ctx())); assert!(!Options().check(&get_req.guard_ctx())); let req = TestRequest::default() .method(Method::CONNECT) .to_srv_request(); assert!(Connect().check(&req.guard_ctx())); assert!(!Connect().check(&get_req.guard_ctx())); let req = TestRequest::default() .method(Method::TRACE) .to_srv_request(); assert!(Trace().check(&req.guard_ctx())); assert!(!Trace().check(&get_req.guard_ctx())); } #[test] fn aggregate_any() { let req = TestRequest::default() .method(Method::TRACE) .to_srv_request(); assert!(Any(Trace()).check(&req.guard_ctx())); assert!(Any(Trace()).or(Get()).check(&req.guard_ctx())); assert!(!Any(Get()).or(Get()).check(&req.guard_ctx())); } #[test] fn aggregate_all() { let req = TestRequest::default() .method(Method::TRACE) .to_srv_request(); assert!(All(Trace()).check(&req.guard_ctx())); assert!(All(Trace()).and(Trace()).check(&req.guard_ctx())); assert!(!All(Trace()).and(Get()).check(&req.guard_ctx())); } #[test] fn nested_not() { let req = TestRequest::default().to_srv_request(); let get = Get(); assert!(get.check(&req.guard_ctx())); let not_get = Not(get); assert!(!not_get.check(&req.guard_ctx())); let not_not_get = Not(not_get); assert!(not_not_get.check(&req.guard_ctx())); } #[test] fn function_guard() { let domain = "rust-lang.org".to_owned(); let guard = fn_guard(|ctx| ctx.head().uri.host().unwrap().ends_with(&domain)); let req = TestRequest::default() .uri("blog.rust-lang.org") .to_srv_request(); assert!(guard.check(&req.guard_ctx())); let req = TestRequest::default().uri("crates.io").to_srv_request(); assert!(!guard.check(&req.guard_ctx())); } #[test] fn mega_nesting() { let guard = fn_guard(|ctx| All(Not(Any(Not(Trace())))).check(ctx)); let req = TestRequest::default().to_srv_request(); assert!(!guard.check(&req.guard_ctx())); let req = TestRequest::default() .method(Method::TRACE) .to_srv_request(); assert!(guard.check(&req.guard_ctx())); } #[test] fn app_data() { const TEST_VALUE: u32 = 42; let guard = fn_guard(|ctx| dbg!(ctx.app_data::<u32>()) == Some(&TEST_VALUE)); let req = TestRequest::default().app_data(TEST_VALUE).to_srv_request(); assert!(guard.check(&req.guard_ctx())); let req = TestRequest::default() .app_data(TEST_VALUE * 2) .to_srv_request(); assert!(!guard.check(&req.guard_ctx())); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/guard/host.rs
actix-web/src/guard/host.rs
use actix_http::{header, uri::Uri, RequestHead, Version}; use super::{Guard, GuardContext}; /// Creates a guard that matches requests targeting a specific host. /// /// # Matching Host /// This guard will: /// - match against the `Host` header, if present; /// - fall-back to matching against the request target's host, if present; /// - return false if host cannot be determined; /// /// # Matching Scheme /// Optionally, this guard can match against the host's scheme. Set the scheme for matching using /// `Host(host).scheme(protocol)`. If the request's scheme cannot be determined, it will not prevent /// the guard from matching successfully. /// /// # Examples /// The `Host` guard can be used to set up a form of [virtual hosting] within a single app. /// Overlapping scope prefixes are usually discouraged, but when combined with non-overlapping guard /// definitions they become safe to use in this way. Without these host guards, only routes under /// the first-to-be-defined scope would be accessible. You can test this locally using `127.0.0.1` /// and `localhost` as the `Host` guards. /// ``` /// use actix_web::{web, http::Method, guard, App, HttpResponse}; /// /// App::new() /// .service( /// web::scope("") /// .guard(guard::Host("www.rust-lang.org")) /// .default_service(web::to(|| async { /// HttpResponse::Ok().body("marketing site") /// })), /// ) /// .service( /// web::scope("") /// .guard(guard::Host("play.rust-lang.org")) /// .default_service(web::to(|| async { /// HttpResponse::Ok().body("playground frontend") /// })), /// ); /// ``` /// /// The example below additionally guards on the host URI's scheme. This could allow routing to /// different handlers for `http:` vs `https:` visitors; to redirect, for example. /// ``` /// use actix_web::{web, guard::Host, HttpResponse}; /// /// web::scope("/admin") /// .guard(Host("admin.rust-lang.org").scheme("https")) /// .default_service(web::to(|| async { /// HttpResponse::Ok().body("admin connection is secure") /// })); /// ``` /// /// [virtual hosting]: https://en.wikipedia.org/wiki/Virtual_hosting #[allow(non_snake_case)] pub fn Host(host: impl AsRef<str>) -> HostGuard { HostGuard { host: host.as_ref().to_string(), scheme: None, } } fn get_host_uri(req: &RequestHead) -> Option<Uri> { req.headers .get(header::HOST) .and_then(|host_value| host_value.to_str().ok()) .filter(|_| req.version < Version::HTTP_2) .or_else(|| req.uri.host()) .and_then(|host| host.parse().ok()) } #[doc(hidden)] pub struct HostGuard { host: String, scheme: Option<String>, } impl HostGuard { /// Set request scheme to match pub fn scheme<H: AsRef<str>>(mut self, scheme: H) -> HostGuard { self.scheme = Some(scheme.as_ref().to_string()); self } } impl Guard for HostGuard { fn check(&self, ctx: &GuardContext<'_>) -> bool { // parse host URI from header or request target let req_host_uri = match get_host_uri(ctx.head()) { Some(uri) => uri, // no match if host cannot be determined None => return false, }; match req_host_uri.host() { // fall through to scheme checks Some(uri_host) if self.host == uri_host => {} // Either: // - request's host does not match guard's host; // - It was possible that the parsed URI from request target did not contain a host. _ => return false, } if let Some(ref scheme) = self.scheme { if let Some(ref req_host_uri_scheme) = req_host_uri.scheme_str() { return scheme == req_host_uri_scheme; } // TODO: is this the correct behavior? // falls through if scheme cannot be determined } // all conditions passed true } } #[cfg(test)] mod tests { use super::*; use crate::test::TestRequest; #[test] fn host_not_from_header_if_http2() { let req = TestRequest::default() .uri("www.rust-lang.org") .insert_header(( header::HOST, header::HeaderValue::from_static("www.example.com"), )) .to_srv_request(); let host = Host("www.example.com"); assert!(host.check(&req.guard_ctx())); let host = Host("www.rust-lang.org"); assert!(!host.check(&req.guard_ctx())); let req = TestRequest::default() .version(actix_http::Version::HTTP_2) .uri("www.rust-lang.org") .insert_header(( header::HOST, header::HeaderValue::from_static("www.example.com"), )) .to_srv_request(); let host = Host("www.example.com"); assert!(!host.check(&req.guard_ctx())); let host = Host("www.rust-lang.org"); assert!(host.check(&req.guard_ctx())); } #[test] fn host_from_header() { let req = TestRequest::default() .insert_header(( header::HOST, header::HeaderValue::from_static("www.rust-lang.org"), )) .to_srv_request(); let host = Host("www.rust-lang.org"); assert!(host.check(&req.guard_ctx())); let host = Host("www.rust-lang.org").scheme("https"); assert!(host.check(&req.guard_ctx())); let host = Host("blog.rust-lang.org"); assert!(!host.check(&req.guard_ctx())); let host = Host("blog.rust-lang.org").scheme("https"); assert!(!host.check(&req.guard_ctx())); let host = Host("crates.io"); assert!(!host.check(&req.guard_ctx())); let host = Host("localhost"); assert!(!host.check(&req.guard_ctx())); } #[test] fn host_without_header() { let req = TestRequest::default() .uri("www.rust-lang.org") .to_srv_request(); let host = Host("www.rust-lang.org"); assert!(host.check(&req.guard_ctx())); let host = Host("www.rust-lang.org").scheme("https"); assert!(host.check(&req.guard_ctx())); let host = Host("blog.rust-lang.org"); assert!(!host.check(&req.guard_ctx())); let host = Host("blog.rust-lang.org").scheme("https"); assert!(!host.check(&req.guard_ctx())); let host = Host("crates.io"); assert!(!host.check(&req.guard_ctx())); let host = Host("localhost"); assert!(!host.check(&req.guard_ctx())); } #[test] fn host_scheme() { let req = TestRequest::default() .insert_header(( header::HOST, header::HeaderValue::from_static("https://www.rust-lang.org"), )) .to_srv_request(); let host = Host("www.rust-lang.org").scheme("https"); assert!(host.check(&req.guard_ctx())); let host = Host("www.rust-lang.org"); assert!(host.check(&req.guard_ctx())); let host = Host("www.rust-lang.org").scheme("http"); assert!(!host.check(&req.guard_ctx())); let host = Host("blog.rust-lang.org"); assert!(!host.check(&req.guard_ctx())); let host = Host("blog.rust-lang.org").scheme("https"); assert!(!host.check(&req.guard_ctx())); let host = Host("crates.io").scheme("https"); assert!(!host.check(&req.guard_ctx())); let host = Host("localhost"); assert!(!host.check(&req.guard_ctx())); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web/src/response/builder.rs
actix-web/src/response/builder.rs
use std::{ cell::{Ref, RefMut}, future::Future, pin::Pin, task::{Context, Poll}, }; use actix_http::{error::HttpError, Response, ResponseHead}; use bytes::Bytes; use futures_core::Stream; use serde::Serialize; use crate::{ body::{BodyStream, BoxBody, MessageBody, SizedStream}, dev::Extensions, error::{Error, JsonPayloadError}, http::{ header::{self, HeaderName, TryIntoHeaderPair, TryIntoHeaderValue}, ConnectionType, StatusCode, }, BoxError, HttpRequest, HttpResponse, Responder, }; /// An HTTP response builder. /// /// This type can be used to construct an instance of `Response` through a builder-like pattern. pub struct HttpResponseBuilder { res: Option<Response<BoxBody>>, error: Option<HttpError>, } impl HttpResponseBuilder { #[inline] /// Create response builder pub fn new(status: StatusCode) -> Self { Self { res: Some(Response::with_body(status, BoxBody::new(()))), error: None, } } /// Set HTTP status code of this response. #[inline] pub fn status(&mut self, status: StatusCode) -> &mut Self { if let Some(parts) = self.inner() { parts.status = status; } self } /// Insert a header, replacing any that were set with an equivalent field name. /// /// ``` /// use actix_web::{HttpResponse, http::header}; /// /// HttpResponse::Ok() /// .insert_header(header::ContentType(mime::APPLICATION_JSON)) /// .insert_header(("X-TEST", "value")) /// .finish(); /// ``` pub fn insert_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self { if let Some(parts) = self.inner() { match header.try_into_pair() { Ok((key, value)) => { parts.headers.insert(key, value); } Err(err) => self.error = Some(err.into()), }; } self } /// Append a header, keeping any that were set with an equivalent field name. /// /// ``` /// use actix_web::{HttpResponse, http::header}; /// /// HttpResponse::Ok() /// .append_header(header::ContentType(mime::APPLICATION_JSON)) /// .append_header(("X-TEST", "value1")) /// .append_header(("X-TEST", "value2")) /// .finish(); /// ``` pub fn append_header(&mut self, header: impl TryIntoHeaderPair) -> &mut Self { if let Some(parts) = self.inner() { match header.try_into_pair() { Ok((key, value)) => parts.headers.append(key, value), Err(err) => self.error = Some(err.into()), }; } self } /// Replaced with [`Self::insert_header()`]. #[doc(hidden)] #[deprecated( since = "4.0.0", note = "Replaced with `insert_header((key, value))`. Will be removed in v5." )] pub fn set_header<K, V>(&mut self, key: K, value: V) -> &mut Self where K: TryInto<HeaderName>, K::Error: Into<HttpError>, V: TryIntoHeaderValue, { if self.error.is_some() { return self; } match (key.try_into(), value.try_into_value()) { (Ok(name), Ok(value)) => return self.insert_header((name, value)), (Err(err), _) => self.error = Some(err.into()), (_, Err(err)) => self.error = Some(err.into()), } self } /// Replaced with [`Self::append_header()`]. #[doc(hidden)] #[deprecated( since = "4.0.0", note = "Replaced with `append_header((key, value))`. Will be removed in v5." )] pub fn header<K, V>(&mut self, key: K, value: V) -> &mut Self where K: TryInto<HeaderName>, K::Error: Into<HttpError>, V: TryIntoHeaderValue, { if self.error.is_some() { return self; } match (key.try_into(), value.try_into_value()) { (Ok(name), Ok(value)) => return self.append_header((name, value)), (Err(err), _) => self.error = Some(err.into()), (_, Err(err)) => self.error = Some(err.into()), } self } /// Set the custom reason for the response. #[inline] pub fn reason(&mut self, reason: &'static str) -> &mut Self { if let Some(parts) = self.inner() { parts.reason = Some(reason); } self } /// Set connection type to KeepAlive #[inline] pub fn keep_alive(&mut self) -> &mut Self { if let Some(parts) = self.inner() { parts.set_connection_type(ConnectionType::KeepAlive); } self } /// Set connection type to Upgrade #[inline] pub fn upgrade<V>(&mut self, value: V) -> &mut Self where V: TryIntoHeaderValue, { if let Some(parts) = self.inner() { parts.set_connection_type(ConnectionType::Upgrade); } if let Ok(value) = value.try_into_value() { self.insert_header((header::UPGRADE, value)); } self } /// Force close connection, even if it is marked as keep-alive #[inline] pub fn force_close(&mut self) -> &mut Self { if let Some(parts) = self.inner() { parts.set_connection_type(ConnectionType::Close); } self } /// Disable chunked transfer encoding for HTTP/1.1 streaming responses. #[inline] pub fn no_chunking(&mut self, len: u64) -> &mut Self { let mut buf = itoa::Buffer::new(); self.insert_header((header::CONTENT_LENGTH, buf.format(len))); if let Some(parts) = self.inner() { parts.no_chunking(true); } self } /// Set response content type. #[inline] pub fn content_type<V>(&mut self, value: V) -> &mut Self where V: TryIntoHeaderValue, { if let Some(parts) = self.inner() { match value.try_into_value() { Ok(value) => { parts.headers.insert(header::CONTENT_TYPE, value); } Err(err) => self.error = Some(err.into()), }; } self } /// Add a cookie to the response. /// /// To send a "removal" cookie, call [`.make_removal()`](cookie::Cookie::make_removal) on the /// given cookie. See [`HttpResponse::add_removal_cookie()`] to learn more. /// /// # Examples /// Send a new cookie: /// ``` /// use actix_web::{HttpResponse, cookie::Cookie}; /// /// let res = HttpResponse::Ok() /// .cookie( /// Cookie::build("name", "value") /// .domain("www.rust-lang.org") /// .path("/") /// .secure(true) /// .http_only(true) /// .finish(), /// ) /// .finish(); /// ``` /// /// Send a removal cookie: /// ``` /// use actix_web::{HttpResponse, cookie::Cookie}; /// /// // the name, domain and path match the cookie created in the previous example /// let mut cookie = Cookie::build("name", "value-does-not-matter") /// .domain("www.rust-lang.org") /// .path("/") /// .finish(); /// cookie.make_removal(); /// /// let res = HttpResponse::Ok() /// .cookie(cookie) /// .finish(); /// ``` #[cfg(feature = "cookies")] pub fn cookie(&mut self, cookie: cookie::Cookie<'_>) -> &mut Self { match cookie.to_string().try_into_value() { Ok(hdr_val) => self.append_header((header::SET_COOKIE, hdr_val)), Err(err) => { self.error = Some(err.into()); self } } } /// Returns a reference to the response-local data/extensions container. #[inline] pub fn extensions(&self) -> Ref<'_, Extensions> { self.res .as_ref() .expect("cannot reuse response builder") .extensions() } /// Returns a mutable reference to the response-local data/extensions container. #[inline] pub fn extensions_mut(&mut self) -> RefMut<'_, Extensions> { self.res .as_mut() .expect("cannot reuse response builder") .extensions_mut() } /// Set a body and build the `HttpResponse`. /// /// Unlike [`message_body`](Self::message_body), errors are converted into error /// responses immediately. /// /// `HttpResponseBuilder` can not be used after this call. pub fn body<B>(&mut self, body: B) -> HttpResponse<BoxBody> where B: MessageBody + 'static, { match self.message_body(body) { Ok(res) => res.map_into_boxed_body(), Err(err) => HttpResponse::from_error(err), } } /// Set a body and build the `HttpResponse`. /// /// `HttpResponseBuilder` can not be used after this call. pub fn message_body<B>(&mut self, body: B) -> Result<HttpResponse<B>, Error> { if let Some(err) = self.error.take() { return Err(err.into()); } let res = self .res .take() .expect("cannot reuse response builder") .set_body(body); Ok(HttpResponse::from(res)) } /// Set a streaming body and build the `HttpResponse`. /// /// `HttpResponseBuilder` can not be used after this call. /// /// If `Content-Type` is not set, then it is automatically set to `application/octet-stream`. /// /// If `Content-Length` is set, then [`no_chunking()`](Self::no_chunking) is automatically called. #[inline] pub fn streaming<S, E>(&mut self, stream: S) -> HttpResponse where S: Stream<Item = Result<Bytes, E>> + 'static, E: Into<BoxError> + 'static, { // Set mime type to application/octet-stream if it is not set if let Some(parts) = self.inner() { if !parts.headers.contains_key(header::CONTENT_TYPE) { self.insert_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM)); } } let content_length = self .inner() .and_then(|parts| parts.headers.get(header::CONTENT_LENGTH)) .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse::<u64>().ok()); if let Some(len) = content_length { self.no_chunking(len); self.body(SizedStream::new(len, stream)) } else { self.body(BodyStream::new(stream)) } } /// Set a JSON body and build the `HttpResponse`. /// /// `HttpResponseBuilder` can not be used after this call. pub fn json(&mut self, value: impl Serialize) -> HttpResponse { match serde_json::to_string(&value) { Ok(body) => { let contains = if let Some(parts) = self.inner() { parts.headers.contains_key(header::CONTENT_TYPE) } else { true }; if !contains { self.insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)); } self.body(body) } Err(err) => HttpResponse::from_error(JsonPayloadError::Serialize(err)), } } /// Set an empty body and build the `HttpResponse`. /// /// `HttpResponseBuilder` can not be used after this call. #[inline] pub fn finish(&mut self) -> HttpResponse { self.body(()) } /// This method construct new `HttpResponseBuilder` pub fn take(&mut self) -> Self { Self { res: self.res.take(), error: self.error.take(), } } fn inner(&mut self) -> Option<&mut ResponseHead> { if self.error.is_some() { return None; } self.res.as_mut().map(Response::head_mut) } } impl From<HttpResponseBuilder> for HttpResponse { fn from(mut builder: HttpResponseBuilder) -> Self { builder.finish() } } impl From<HttpResponseBuilder> for Response<BoxBody> { fn from(mut builder: HttpResponseBuilder) -> Self { builder.finish().into() } } impl Future for HttpResponseBuilder { type Output = Result<HttpResponse, Error>; fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> { Poll::Ready(Ok(self.finish())) } } impl Responder for HttpResponseBuilder { type Body = BoxBody; #[inline] fn respond_to(mut self, _: &HttpRequest) -> HttpResponse<Self::Body> { self.finish() } } #[cfg(test)] mod tests { use super::*; use crate::{ body, http::header::{HeaderValue, CONTENT_TYPE}, test::assert_body_eq, }; #[test] fn test_basic_builder() { let resp = HttpResponse::Ok() .insert_header(("X-TEST", "value")) .finish(); assert_eq!(resp.status(), StatusCode::OK); } #[test] fn test_upgrade() { let resp = HttpResponseBuilder::new(StatusCode::OK) .upgrade("websocket") .finish(); assert!(resp.upgrade()); assert_eq!( resp.headers().get(header::UPGRADE).unwrap(), HeaderValue::from_static("websocket") ); } #[test] fn test_force_close() { let resp = HttpResponseBuilder::new(StatusCode::OK) .force_close() .finish(); assert!(!resp.keep_alive()) } #[test] fn test_content_type() { let resp = HttpResponseBuilder::new(StatusCode::OK) .content_type("text/plain") .body(Bytes::new()); assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain") } #[actix_rt::test] async fn test_json() { let res = HttpResponse::Ok().json(vec!["v1", "v2", "v3"]); let ct = res.headers().get(CONTENT_TYPE).unwrap(); assert_eq!(ct, HeaderValue::from_static("application/json")); assert_body_eq!(res, br#"["v1","v2","v3"]"#); let res = HttpResponse::Ok().json(["v1", "v2", "v3"]); let ct = res.headers().get(CONTENT_TYPE).unwrap(); assert_eq!(ct, HeaderValue::from_static("application/json")); assert_body_eq!(res, br#"["v1","v2","v3"]"#); // content type override let res = HttpResponse::Ok() .insert_header((CONTENT_TYPE, "text/json")) .json(["v1", "v2", "v3"]); let ct = res.headers().get(CONTENT_TYPE).unwrap(); assert_eq!(ct, HeaderValue::from_static("text/json")); assert_body_eq!(res, br#"["v1","v2","v3"]"#); } #[actix_rt::test] async fn test_serde_json_in_body() { let resp = HttpResponse::Ok() .body(serde_json::to_vec(&serde_json::json!({ "test-key": "test-value" })).unwrap()); assert_eq!( body::to_bytes(resp.into_body()).await.unwrap().as_ref(), br#"{"test-key":"test-value"}"# ); } #[test] fn response_builder_header_insert_kv() { let mut res = HttpResponse::Ok(); res.insert_header(("Content-Type", "application/octet-stream")); let res = res.finish(); assert_eq!( res.headers().get("Content-Type"), Some(&HeaderValue::from_static("application/octet-stream")) ); } #[test] fn response_builder_header_insert_typed() { let mut res = HttpResponse::Ok(); res.insert_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM)); let res = res.finish(); assert_eq!( res.headers().get("Content-Type"), Some(&HeaderValue::from_static("application/octet-stream")) ); } #[test] fn response_builder_header_append_kv() { let mut res = HttpResponse::Ok(); res.append_header(("Content-Type", "application/octet-stream")); res.append_header(("Content-Type", "application/json")); let res = res.finish(); let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect(); assert_eq!(headers.len(), 2); assert!(headers.contains(&HeaderValue::from_static("application/octet-stream"))); assert!(headers.contains(&HeaderValue::from_static("application/json"))); } #[test] fn response_builder_header_append_typed() { let mut res = HttpResponse::Ok(); res.append_header((header::CONTENT_TYPE, mime::APPLICATION_OCTET_STREAM)); res.append_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)); let res = res.finish(); let headers: Vec<_> = res.headers().get_all("Content-Type").cloned().collect(); assert_eq!(headers.len(), 2); assert!(headers.contains(&HeaderValue::from_static("application/octet-stream"))); assert!(headers.contains(&HeaderValue::from_static("application/json"))); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false