id stringlengths 20 30 | source stringclasses 1
value | chunk_index int64 0 520k | token_count int32 154 512 | content stringlengths 185 57.5k |
|---|---|---|---|---|
rust_dataset_chunk_1100 | rust_dataset.txt | 1,100 | 512 | _static("0001"));
Ok(res)
}
})
.route("/test", web::get().to(HttpResponse::Ok)),
),
)
.await;
let req = TestRequest::with_uri("/app/test").to_request();
let resp = call_service(&srv, ... |
rust_dataset_chunk_1101 | rust_dataset.txt | 1,101 | 512 | !(resp.status(), StatusCode::OK);
}
// allow deprecated `{App, Scope}::data`
#[allow(deprecated)]
#[tokio::test(flavor = "local")]
async fn test_override_data_default_service() {
let srv =
init_service(App::new().data(1usize).service(
web::scope("app").data(10usi... |
rust_dataset_chunk_1102 | rust_dataset.txt | 1,102 | 512 | app/v1/").to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
}
#[tokio::test(flavor = "local")]
async fn test_url_for_external() {
let srv = init_service(App::new().service(web::scope("/app").configure(|s| {
s.service(web::s... |
rust_dataset_chunk_1103 | rust_dataset.txt | 1,103 | 512 | )
.route("/{c}", web::get().to(|_: HttpRequest| HttpResponse::Ok())),
),
),
)
.await;
// note the unintuitive behavior with trailing slashes on scopes with dynamic segments
let req = TestRequest::with_uri("/a//b... |
rust_dataset_chunk_1104 | rust_dataset.txt | 1,104 | 512 | ,
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::{GracefulShutdownSignal... |
rust_dataset_chunk_1105 | rust_dataset.txt | 1,105 | 512 | ///
/// #[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 HttpSe... |
rust_dataset_chunk_1106 | rust_dataset.txt | 1,106 | 512 | _shutdown_signal = builder.graceful_shutdown_signal();
HttpServer {
factory,
config: Arc::new(Mutex::new(Config {
host: None,
keep_alive: KeepAlive::default(),
tcp_nodelay: Some(true),
client_request_timeout: Duration::from... |
rust_dataset_chunk_1107 | rust_dataset.txt | 1,107 | 512 | 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 1024.
///
/// This method will have no ef... |
rust_dataset_chunk_1108 | rust_dataset.txt | 1,108 | 512 | ().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.
///
... |
rust_dataset_chunk_1109 | rust_dataset.txt | 1,109 | 512 | /// # Panics
///
/// Panics if `size` is 0.
pub fn h1_write_buffer_size(self, size: usize) -> Self {
assert!(
size > 0,
"HTTP/1 write buffer size must be greater than zero"
);
self.config.lock().unwrap().h1_write_buffer_size = Some(size);
self
... |
rust_dataset_chunk_1110 | rust_dataset.txt | 1,110 | 512 | .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::Tc... |
rust_dataset_chunk_1111 | rust_dataset.txt | 1,111 | 512 | /// 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(("12... |
rust_dataset_chunk_1112 | rust_dataset.txt | 1,112 | 512 | 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.
///
/// # Wo... |
rust_dataset_chunk_1113 | rust_dataset.txt | 1,113 | 512 | - 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((... |
rust_dataset_chunk_1114 | rust_dataset.txt | 1,114 | 512 | /// using Rustls v0.20.
///
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
///
/// The "http/1.1" ALPN protocol is added to any configured ones. The "h2" protocol is also
/// added when the `http2` feature is enabled.
#[cfg(feature = "rustls-0_20")]
pub fn bind_rustl... |
rust_dataset_chunk_1115 | rust_dataset.txt | 1,115 | 512 | 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_... |
rust_dataset_chunk_1116 | rust_dataset.txt | 1,116 | 512 | 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()`.
///
... |
rust_dataset_chunk_1117 | rust_dataset.txt | 1,117 | 512 | _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 |_| {
AppCo... |
rust_dataset_chunk_1118 | rust_dataset.txt | 1,118 | 512 | svc.h2_initial_window_size(val);
}
if let Some(val) = cfg.h2_initial_connection_window_size {
svc = svc.h2_initial_connection_window_size(val);
}
if let Some(handler) = on_connect_fn.clone() {
... |
rust_dataset_chunk_1119 | rust_dataset.txt | 1,119 | 512 | _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.pu... |
rust_dataset_chunk_1120 | rust_dataset.txt | 1,120 | 512 | }))
.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,
)... |
rust_dataset_chunk_1121 | rust_dataset.txt | 1,121 | 512 | handshake_timeout(dur),
None => TlsAcceptorConfig::default(),
};
svc.finish(map_config(fac, move |_| {
AppConfig::new(true, host.clone(), addr)
}))
.rustls_021_with_config(config.clone(), acc... |
rust_dataset_chunk_1122 | rust_dataset.txt | 1,122 | 512 | _allow_half_closed)
.client_disconnect_timeout(c.client_disconnect_timeout);
if let Some(enabled) = c.tcp_nodelay {
svc = svc.tcp_nodelay(enabled);
}
if let Some(size) = c.h1_write_buffer_size {
... |
rust_dataset_chunk_1123 | rust_dataset.txt | 1,123 | 512 | 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... |
rust_dataset_chunk_1124 | rust_dataset.txt | 1,124 | 512 | inds to existing listener for accepting incoming TLS connection requests using OpenSSL.
///
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
///
/// The "http/1.1" ALPN protocol is added to any configured ones. The "h2" protocol is also
/// added when the `http2` feature is... |
rust_dataset_chunk_1125 | rust_dataset.txt | 1,125 | 512 | _window_size(val);
}
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()
... |
rust_dataset_chunk_1126 | rust_dataset.txt | 1,126 | 512 | shutdown_signal = graceful_shutdown_signal.clone();
let mut svc = HttpService::build()
.graceful_shutdown_signal(move || {
let signal = shutdown_signal.clone();
async move { signal.notified().await }
... |
rust_dataset_chunk_1127 | rust_dataset.txt | 1,127 | 512 | _half_closed(c.h1_allow_half_closed)
.client_disconnect_timeout(c.client_disconnect_timeout);
if let Some(handler) = on_connect_fn.clone() {
svc = svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext));
}
if let ... |
rust_dataset_chunk_1128 | rust_dataset.txt | 1,128 | 512 | (addr, backlog) {
Ok(lst) => {
success = true;
sockets.push(lst);
}
Err(error) => err = Some(error),
}
}
if success {
Ok(sockets)
} else if let Some(err) = err.take() {
Err(err)
} else {
Err(io::Error::o... |
rust_dataset_chunk_1129 | rust_dataset.txt | 1,129 | 512 | )
}
});
#[cfg(feature = "http2")]
let protos = b"\x08http/1.1\x02h2";
#[cfg(not(feature = "http2"))]
let protos = b"\x08http/1.1";
builder.set_alpn_protos(protos)?;
Ok(builder.build())
}
--- FILE: actix-web/actix-web/src/service.rs ---
use std::{
cell::{Ref, RefMut},
fmt,... |
rust_dataset_chunk_1130 | rust_dataset.txt | 1,130 | 512 | ) = 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 par... |
rust_dataset_chunk_1131 | rust_dataset.txt | 1,131 | 512 | 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,
}
}... |
rust_dataset_chunk_1132 | rust_dataset.txt | 1,132 | 512 | 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<'_, C... |
rust_dataset_chunk_1133 | rust_dataset.txt | 1,133 | 512 | coding their names and values.
#[cfg(feature = "cookies")]
#[inline]
pub fn cookies_raw(&self) -> Result<Ref<'_, Vec<Cookie<'static>>>, CookieParseError> {
self.req.cookies_raw()
}
/// Return request cookie.
#[cfg(feature = "cookies")]
#[inline]
pub fn cookie(&self, name: &str) ... |
rust_dataset_chunk_1134 | rust_dataset.txt | 1,134 | 512 | ]
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::... |
rust_dataset_chunk_1135 | rust_dataset.txt | 1,135 | 512 | ) -> &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.resp... |
rust_dataset_chunk_1136 | rust_dataset.txt | 1,136 | 512 | 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 {:?} {}{}",... |
rust_dataset_chunk_1137 | rust_dataset.txt | 1,137 | 512 | impl HttpServiceFactory
where
F: IntoServiceFactory<T, ServiceRequest>,
T: ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse,
Error = Error,
InitError = (),
> + 'static,
{
W... |
rust_dataset_chunk_1138 | rust_dataset.txt | 1,138 | 512 | " }))
/// ));
/// ```
#[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(n... |
rust_dataset_chunk_1139 | rust_dataset.txt | 1,139 | 512 | )
.to_request();
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), http::StatusCode::METHOD_NOT_ALLOWED);
}
// allow deprecated App::data
#[allow(deprecated)]
#[tokio::test(flavor = "local")]
async fn test_service_data() {
let srv = init_service(... |
rust_dataset_chunk_1140 | rust_dataset.txt | 1,140 | 512 | }),
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 re... |
rust_dataset_chunk_1141 | rust_dataset.txt | 1,141 | 512 | );
}
#[tokio::test(flavor = "local")]
#[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(... |
rust_dataset_chunk_1142 | rust_dataset.txt | 1,142 | 512 | 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_bod... |
rust_dataset_chunk_1143 | rust_dataset.txt | 1,143 | 512 | ::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");
}
}
--- FILE: actix-web/actix-web/src/test/test_request.rs ---
use std::{borrow::Cow, net::SocketAddr, ... |
rust_dataset_chunk_1144 | rust_dataset.txt | 1,144 | 512 | /// 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: HttpTestReque... |
rust_dataset_chunk_1145 | rust_dataset.txt | 1,145 | 512 | 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
}
... |
rust_dataset_chunk_1146 | rust_dataset.txt | 1,146 | 512 | 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::... |
rust_dataset_chunk_1147 | rust_dataset.txt | 1,147 | 512 | 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_without_pool(Rc::new(self.rmap), self.con... |
rust_dataset_chunk_1148 | rust_dataset.txt | 1,148 | 512 | ::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::{sync::Arc, time::SystemTime};
use super::*;
use crate::{http::header, test::init_service, web, App, Error, Responder}... |
rust_dataset_chunk_1149 | rust_dataset.txt | 1,149 | 512 | {
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")
.... |
rust_dataset_chunk_1150 | rust_dataset.txt | 1,150 | 512 | .
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.
#[expect(deprecated, reason = "preserve the public ready future type")]
pub fn status_service(
... |
rust_dataset_chunk_1151 | rust_dataset.txt | 1,151 | 512 | ics
/// 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>,
... |
rust_dataset_chunk_1152 | rust_dataset.txt | 1,152 | 512 | `] 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 TestReques... |
rust_dataset_chunk_1153 | rust_dataset.txt | 1,153 | 512 | ::Bytes;
///
/// #[tokio::test(flavor = "local")]
/// 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!")
/// ... |
rust_dataset_chunk_1154 | rust_dataset.txt | 1,154 | 512 | 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).... |
rust_dataset_chunk_1155 | rust_dataset.txt | 1,155 | 512 | .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 a... |
rust_dataset_chunk_1156 | rust_dataset.txt | 1,156 | 512 | Ok().body("put!")))
.route(web::patch().to(|| HttpResponse::Ok().body("patch!")))
.route(web::query().to(|| HttpResponse::Ok().body("query!")))
.route(web::delete().to(|| HttpResponse::Ok().body("delete!"))),
),
)
.await;
l... |
rust_dataset_chunk_1157 | rust_dataset.txt | 1,157 | 512 | (&app, req).await;
assert_eq!(result.id, "12345");
assert_eq!(result.name, "User name");
}
#[derive(Serialize, Deserialize, Debug)]
pub struct Person {
id: String,
name: String,
}
#[tokio::test(flavor = "local")]
async fn test_response_json() {
let app =... |
rust_dataset_chunk_1158 | rust_dataset.txt | 1,158 | 512 | "application/json"))
.set_payload(payload)
.send_request(&app)
.await;
let result: Person = read_body_json(res).await;
assert_eq!(&result.name, "User name");
}
#[tokio::test(flavor = "local")]
async fn test_try_body_json_error() {
let app =
... |
rust_dataset_chunk_1159 | rust_dataset.txt | 1,159 | 512 | .to_request();
let result = call_and_read_body(&app, req).await;
assert_eq!(result, Bytes::from_static(b"welcome!"));
}
#[tokio::test(flavor = "local")]
async fn test_request_response_json() {
let app =
init_service(App::new().service(web::resource("/people").route(
... |
rust_dataset_chunk_1160 | rust_dataset.txt | 1,160 | 512 | _name;
#[expect(deprecated, reason = "preserve the public ready future type")]
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... |
rust_dataset_chunk_1161 | rust_dataset.txt | 1,161 | 512 | 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... |
rust_dataset_chunk_1162 | rust_dataset.txt | 1,162 | 512 | 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 fo... |
rust_dataset_chunk_1163 | rust_dataset.txt | 1,163 | 512 | 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 {
... |
rust_dataset_chunk_1164 | rust_dataset.txt | 1,164 | 512 | ::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... |
rust_dataset_chunk_1165 | rust_dataset.txt | 1,165 | 512 | => {
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));
Eithe... |
rust_dataset_chunk_1166 | rust_dataset.txt | 1,166 | 512 | >, Json<TestForm>>::from_request(&req, &mut pl)
.await
.unwrap()
.unwrap_right()
.into_inner();
assert_eq!(&form.hello, "world");
}
#[tokio::test(flavor = "local")]
async fn test_either_extract_recursive_fallback() {
let (req, mut pl) = TestRe... |
rust_dataset_chunk_1167 | rust_dataset.txt | 1,167 | 512 | .
///
/// # 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)]
//... |
rust_dataset_chunk_1168 | rust_dataset.txt | 1,168 | 512 | &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.seri... |
rust_dataset_chunk_1169 | rust_dataset.txt | 1,169 | 512 | 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(... |
rust_dataset_chunk_1170 | rust_dataset.txt | 1,170 | 512 | DEFAULT_LIMIT: usize = 32_768; // 32 KiB
/// Allow shared refs used as default.
const DEFAULT_CONFIG: FormConfig = FormConfig {
limit: DEFAULT_LIMIT,
err_handler: None,
};
impl Default for FormConfig {
fn default() -> Self {
DEFAULT_CONFIG
}
}
/// Future that resolves to some `T` when parsed... |
rust_dataset_chunk_1171 | rust_dataset.txt | 1,171 | 512 | Some(payload),
limit: DEFAULT_LIMIT,
length: len,
fut: None,
err: None,
}
}
fn err(err: UrlencodedError) -> Self {
UrlEncoded {
stream: None,
limit: DEFAULT_LIMIT,
fut: None,
err: Some(err),
... |
rust_dataset_chunk_1172 | rust_dataset.txt | 1,172 | 512 | _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 se... |
rust_dataset_chunk_1173 | rust_dataset.txt | 1,173 | 512 | .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"))
... |
rust_dataset_chunk_1174 | rust_dataset.txt | 1,174 | 512 | counter=123");
}
#[tokio::test(flavor = "local")]
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... |
rust_dataset_chunk_1175 | rust_dataset.txt | 1,175 | 512 | }
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)
}
}
#[expect(deprecated, reason = "preserve the public ready future type")]
impl<T> FromRequest for Header<T>
where
T: ParseHeader,
{
type ... |
rust_dataset_chunk_1176 | rust_dataset.txt | 1,176 | 512 | !</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: &HttpReq... |
rust_dataset_chunk_1177 | rust_dataset.txt | 1,177 | 512 | ///
/// ```
/// 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.user... |
rust_dataset_chunk_1178 | rust_dataset.txt | 1,178 | 512 | Body<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... |
rust_dataset_chunk_1179 | rust_dataset.txt | 1,179 | 512 | };
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 bou... |
rust_dataset_chunk_1180 | rust_dataset.txt | 1,180 | 512 | 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>()
... |
rust_dataset_chunk_1181 | rust_dataset.txt | 1,181 | 512 | ()) {
(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
... |
rust_dataset_chunk_1182 | rust_dataset.txt | 1,182 | 512 | > {
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 {
... |
rust_dataset_chunk_1183 | rust_dataset.txt | 1,183 | 512 | unwrap(),
header::HeaderValue::from_static("application/json")
);
assert_body_eq!(res, b"{\"name\":\"test\"}");
}
#[tokio::test(flavor = "local")]
async fn test_custom_error_responder() {
let (req, mut pl) = TestRequest::default()
.insert_header((
... |
rust_dataset_chunk_1184 | rust_dataset.txt | 1,184 | 512 | 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().u... |
rust_dataset_chunk_1185 | rust_dataset.txt | 1,185 | 512 | 100)
.await;
assert!(json_eq(
json.err().unwrap(),
JsonPayloadError::OverflowKnownLength {
length: 10000,
limit: 100
}
));
let (mut req, mut pl) = TestRequest::default()
.insert_header((
... |
rust_dataset_chunk_1186 | rust_dataset.txt | 1,186 | 512 | ((
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\": \"t... |
rust_dataset_chunk_1187 | rust_dataset.txt | 1,187 | 512 | ::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(... |
rust_dataset_chunk_1188 | rust_dataset.txt | 1,188 | 512 | 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}... |
rust_dataset_chunk_1189 | rust_dataset.txt | 1,189 | 512 | type")]
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>()
... |
rust_dataset_chunk_1190 | rust_dataset.txt | 1,190 | 512 | (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, H... |
rust_dataset_chunk_1191 | rust_dataset.txt | 1,191 | 512 | = <()>::from_request(&req, &mut pl).await.unwrap();
}
#[tokio::test(flavor = "local")]
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(re... |
rust_dataset_chunk_1192 | rust_dataset.txt | 1,192 | 512 | Def::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();
as... |
rust_dataset_chunk_1193 | rust_dataset.txt | 1,193 | 512 | #[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 {
///... |
rust_dataset_chunk_1194 | rust_dataset.txt | 1,194 | 512 | (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
/... |
rust_dataset_chunk_1195 | rust_dataset.txt | 1,195 | 512 | /// async fn index(body: web::Bytes) -> String {
/// format!("Body {:?}!", body)
/// }
/// ```
#[expect(deprecated, reason = "preserve the public ready future type")]
impl FromRequest for Bytes {
type Error = Error;
type Future = Either<BytesExtractFut, Ready<Result<Bytes, Error>>>;
#[inline]
fn fr... |
rust_dataset_chunk_1196 | rust_dataset.txt | 1,196 | 512 | (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: &'st... |
rust_dataset_chunk_1197 | rust_dataset.txt | 1,197 | 512 | .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... |
rust_dataset_chunk_1198 | rust_dataset.txt | 1,198 | 512 | 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);
... |
rust_dataset_chunk_1199 | rust_dataset.txt | 1,199 | 512 | _service, read_body, TestRequest},
App, Responder,
};
#[tokio::test(flavor = "local")]
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) -> c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.