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_700 | rust_dataset.txt | 700 | 512 | ceeded() {
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)
... |
rust_dataset_chunk_701 | rust_dataset.txt | 701 | 512 | .start()
},
))
});
common_test_code(srv, DEFAULT_FRAME_SIZE).await;
}
#[tokio::test(flavor = "local")]
async fn builder_full() {
let srv = actix_test::start(|| {
App::new().service(web::resource("/").to(
|req: HttpRequest, stream: web::Payload| a... |
rust_dataset_chunk_702 | rust_dataset.txt | 702 | 512 | > {
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self.0)
}
}
fn future_responder(c: &mut Criterion) {
let rt = actix_rt::System::new();
let req = TestRequest::default().to_http_request();
c.bench_function("future_responder", move ... |
rust_dataset_chunk_703 | rust_dataset.txt | 703 | 512 | World Hello World \
Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World Hello World Hello World \
Hello World Hello World Hello World H... |
rust_dataset_chunk_704 | rust_dataset.txt | 704 | 512 | , HttpResponse,
};
use criterion::{criterion_main, Criterion};
/// Criterion Benchmark for async Service
/// Should be used from within criterion group:
/// ```ignore
/// let mut criterion: ::criterion::Criterion<_> =
/// ::criterion::Criterion::default().configure_from_args();
/// bench_async_service(&mut criteri... |
rust_dataset_chunk_705 | rust_dataset.txt | 705 | 512 | let rt = actix_rt::System::new();
let srv = Rc::new(RefCell::new(rt.block_on(init_service(
App::new().service(web::service("/").finish(index)),
))));
let req = TestRequest::get().uri("/").to_request();
assert!(rt
.block_on(srv.borrow_mut().call(req))
.unwrap()
.status()... |
rust_dataset_chunk_706 | rust_dataset.txt | 706 | 512 | handler for each of the most common HTTP methods that also define
//! additional guards and route-specific middleware.
//!
//! See docs for: [GET], [POST], [PATCH], [PUT], [DELETE], [QUERY], [HEAD], [CONNECT], [OPTIONS],
//! [TRACE]
//!
//! ```
//! # use actix_web::HttpResponse;
//! # use actix_web_codegen::get;
//! #... |
rust_dataset_chunk_707 | rust_dataset.txt | 707 | 512 | ```plain
/// #[route("path", method="HTTP_METHOD"[, attributes])]
/// ```
///
/// # Attributes
/// - `"path"`: Raw literal string with path for which to register handler.
/// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the function
/// name of handler is used.
/// - `method = "HT... |
rust_dataset_chunk_708 | rust_dataset.txt | 708 | 512 | TokenStream) -> TokenStream {
route::with_methods(input)
}
macro_rules! method_macro {
($variant:ident, $method:ident) => {
#[doc = concat!("Creates route handler with `actix_web::guard::", stringify!($variant), "`.")]
///
/// # Syntax
/// ```plain
#[doc = concat!("#[",... |
rust_dataset_chunk_709 | rust_dataset.txt | 709 | 512 | /// mod api {
/// // ...
/// }
/// ```
///
/// # Arguments
///
/// - `"/prefix"` - Raw literal string to be prefixed onto contained handlers' paths.
///
/// # Example
///
/// ```
/// # use actix_web_codegen::{scope, get};
/// # use actix_web::Responder;
/// #[scope("/api")]
/// mod api {
/// # use super::*;
///... |
rust_dataset_chunk_710 | rust_dataset.txt | 710 | 512 | Returning the original input in addition to the error is good for IDEs which can gracefully
/// recover and show more precise errors within the macro body.
///
/// See <https://github.com/rust-analyzer/rust-analyzer/issues/10468> for more info.
fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> Toke... |
rust_dataset_chunk_711 | rust_dataset.txt | 711 | 512 | parse, Token![,])?;
Ok(Self { path, options })
}
}
macro_rules! standard_method_type {
(
$($variant:ident, $upper:ident, $lower:ident,)+
) => {
#[doc(hidden)]
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum MethodType {
$(
$variant,... |
rust_dataset_chunk_712 | rust_dataset.txt | 712 | 512 | TypeExt::Standard(method) => {
quote! {
.guard(::actix_web::guard::#method())
}
}
MethodTypeExt::Custom(lit) => {
quote! {
.guard(::actix_web::guard::Method(
::actix_web::http::Method:... |
rust_dataset_chunk_713 | rust_dataset.txt | 713 | 512 | ::LitStr> for MethodTypeExt {
type Error = syn::Error;
fn try_from(value: &syn::LitStr) -> Result<Self, Self::Error> {
match MethodType::try_from(value) {
Ok(method) => Ok(MethodTypeExt::Standard(method)),
Err(_) if value.value().chars().all(|c| c.is_ascii_uppercase()) => {
... |
rust_dataset_chunk_714 | rust_dataset.txt | 714 | 512 | "Attribute guard_obj expects a guard expression; remove the surrounding quotes",
));
}
guard_objs.push(nv.value);
} else if nv.path.is_ident("wrap") {
if let syn::Expr::Lit(syn::ExprLit {
lit: syn::Lit::Str(lit),
... |
rust_dataset_chunk_715 | rust_dataset.txt | 715 | 512 | // Try and pull out the doc comments so that we can reapply them to the generated struct.
// Note that multi line doc comments are converted to multiple doc attributes.
let doc_attributes = ast
.attrs
.iter()
.filter(|attr| attr.path().is_ident("doc"))
.c... |
rust_dataset_chunk_716 | rust_dataset.txt | 716 | 512 | map(|args| {
let Args {
path,
resource_name,
guards,
guard_objs,
wrappers,
methods,
} = args;
let resource_name = resource_name
.as... |
rust_dataset_chunk_717 | rust_dataset.txt | 717 | 512 | => route.into_token_stream().into(),
// on macro related error, make IDEs happy; see fn docs
Err(err) => input_and_compile_error(input, err),
}
}
pub(crate) fn with_methods(input: TokenStream) -> TokenStream {
let mut ast = match syn::parse::<syn::ItemFn>(input.clone()) {
Ok(ast) => as... |
rust_dataset_chunk_718 | rust_dataset.txt | 718 | 512 | if args.is_empty() {
return Err(syn::Error::new(
Span::call_site(),
"missing arguments for scope macro, expected: #[scope(\"/prefix\")]",
));
}
let scope_prefix = syn::parse::<syn::LitStr>(args.clone()).map_err(|err| {
syn::Error::new(
err.span(),
... |
rust_dataset_chunk_719 | rust_dataset.txt | 719 | 512 | =
options_tokens
.into_iter()
.fold(TokenStream2::new(), |mut acc, ts| {
acc.extend(std::iter::once(ts));
acc
});
syn::Attribute {
meta: syn::Meta::List(syn::MetaList... |
rust_dataset_chunk_720 | rust_dataset.txt | 720 | 512 | actix_web::Error>> {
ready(Ok(HttpResponse::Ok().finish()))
}
#[get("/test")]
fn auto_sync() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> {
ready(Ok(HttpResponse::Ok().finish()))
}
#[put("/test/{param}")]
async fn put_param_test(_: web::Path<String>) -> impl Responder {
HttpResponse::C... |
rust_dataset_chunk_721 | rust_dataset.txt | 721 | 512 | _resource_name_test").is_err());
HttpResponse::Ok()
}
mod guard_module {
use actix_web::{guard::GuardContext, http::header};
pub fn guard(ctx: &GuardContext<'_>) -> bool {
ctx.header::<header::Accept>()
.map(|h| h.preference() == "image/*")
.unwrap_or(false)
}
}
#[get(... |
rust_dataset_chunk_722 | rust_dataset.txt | 722 | 512 | https://github.com/actix/actix-web/issues/3118>.
#[route(
"/catalog",
method = "GET",
method = "HEAD",
wrap = "actix_web::middleware::Compress::default()"
)]
async fn get_catalog() -> impl Responder {
HttpResponse::Ok().body("123123123")
}
#[tokio::test(flavor = "local")]
async fn test_params() {
... |
rust_dataset_chunk_723 | rust_dataset.txt | 723 | 512 | "));
let response = request.send().await.unwrap();
assert!(response.status().is_success());
let request = srv.request(http::Method::TRACE, srv.url("/test"));
let response = request.send().await.unwrap();
assert!(response.status().is_success());
let request = srv.request(http::Method::PATCH, sr... |
rust_dataset_chunk_724 | rust_dataset.txt | 724 | 512 | .unwrap();
assert!(response.status().is_client_error());
let request = srv.request(http::Method::GET, srv.url("/routes/overlap/test"));
let response = request.send().await.unwrap();
assert!(response.status().is_success());
let request = srv.request(http::Method::GET, srv.url("/routes/overlap/bar")... |
rust_dataset_chunk_725 | rust_dataset.txt | 725 | 512 | let request = srv.request(query_method, srv.url("/test"));
let response = request.send().await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let request = srv.request(http::Method::GET, srv.url("/test"));
let response = request.send().await.unwrap();
assert_eq!(response.status(), Sta... |
rust_dataset_chunk_726 | rust_dataset.txt | 726 | 512 | App::new()
.service(g_header)
.service(g_route_macro)
.service(g_coexist)
.service(g_combo)
.service(g_multi_attr)
.service(g_custom)
})
}
async fn req(
srv: &actix_test::TestServer,
method: http::Method,
path: &str,
he... |
rust_dataset_chunk_727 | rust_dataset.txt | 727 | 512 | ")]
)
.await,
StatusCode::METHOD_NOT_ALLOWED
);
}
#[actix_web::test]
async fn test_guard_obj_combinators_and_custom() {
let srv = start_guard_obj_server();
for path in ["/test/guard_obj/combo", "/test/guard_obj/multi_attr"] {
for (headers, expected) in [
(&[("x-... |
rust_dataset_chunk_728 | rust_dataset.txt | 728 | 512 | value: {}", doubled))
}
#[post("/test")]
pub async fn post() -> impl Responder {
HttpResponse::Ok().body("post works")
}
#[delete("/test")]
pub async fn delete() -> impl Responder {
"delete works"
}
#[route("/test", method = "PUT", method = "PATCH", method = "CUSTOM")... |
rust_dataset_chunk_729 | rust_dataset.txt | 729 | 512 | -test/4"));
let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "Twice value: 8");
}
#[tokio::test(flavor = "local")]
async fn scope_post_async() {
let srv = actix_test::start(|| ... |
rust_dataset_chunk_730 | rust_dataset.txt | 730 | 512 | let request = srv.request(http::Method::DELETE, srv.url("/test/test"));
let mut response = request.send().await.unwrap();
let body = response.body().await.unwrap();
let body_str = String::from_utf8(body.to_vec()).unwrap();
assert_eq!(body_str, "delete works");
}
#[tokio::test(flavor = "local")]
async ... |
rust_dataset_chunk_731 | rust_dataset.txt | 731 | 512 | http::Method;
use std::str::FromStr;
#[route("/", method = "hello")]
async fn index() -> String {
"Hello World!".to_owned()
}
#[actix_web::main]
async fn main() {
use actix_web::App;
let srv = actix_test::start(|| App::new().service(index));
let request = srv.request(Method::from_str("hello").unwrap... |
rust_dataset_chunk_732 | rust_dataset.txt | 732 | 512 | await.unwrap();
assert!(response.status().is_success());
}
--- FILE: actix-web/actix-web-codegen/tests/trybuild/route-guard-obj-constructor-fail.rs ---
use actix_web_codegen::get;
#[get("/", guard_obj = actix_web::guard::Get)]
async fn index() -> &'static str {
"ok"
}
fn main() {}
--- FILE: actix-web/acti... |
rust_dataset_chunk_733 | rust_dataset.txt | 733 | 512 | assert!(response.status().is_success());
}
--- FILE: actix-web/actix-web-codegen/tests/trybuild/route-ok.rs ---
use actix_web::guard;
use actix_web_codegen::*;
#[route("/", method="GET", method="HEAD")]
async fn index() -> String {
"Hello World!".to_owned()
}
fn guard_function(_: &guard::GuardContext<'_>) -> b... |
rust_dataset_chunk_734 | rust_dataset.txt | 734 | 512 | ();
assert!(response.status().is_success());
let request = srv.post("/");
let response = request.send().await.unwrap();
assert!(response.status().is_success());
}
--- FILE: actix-web/actix-web-codegen/tests/trybuild.rs ---
#[rustversion_msrv::msrv]
#[test]
fn compile_macros() {
let t = trybuild::... |
rust_dataset_chunk_735 | rust_dataset.txt | 735 | 512 | /scope-on-handler.rs ---
use actix_web_codegen::scope;
#[scope("/api")]
async fn index() -> &'static str {
"Hello World!"
}
fn main() {}
--- FILE: actix-web/actix-web-codegen/tests/trybuild/scope-trailing-slash.rs ---
use actix_web_codegen::scope;
#[scope("/api/")]
mod api {}
fn main() {}
--- FILE: actix-we... |
rust_dataset_chunk_736 | rust_dataset.txt | 736 | 512 | "Hello world!\r\n"
}
#[get("/")]
async fn no_params() -> &'static str {
"Hello world!\r\n"
}
#[tokio::main(flavor = "local")]
async fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
log::info!("starting HTTP server at http://localhost:8080... |
rust_dataset_chunk_737 | rust_dataset.txt | 737 | 512 | }
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::<()>())
}
async fn mutate_body_type_with_extractors(
string_body: String,
query: Query<H... |
rust_dataset_chunk_738 | rust_dataset.txt | 738 | 512 | async fn main() -> io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
let bind = ("127.0.0.1", 8080);
info!("staring server at http://{}:{}", &bind.0, &bind.1);
HttpServer::new(|| {
App::new()
.wrap(from_fn(noop))
.wrap(from_fn... |
rust_dataset_chunk_739 | rust_dataset.txt | 739 | 512 | resource("/introspection").route(web::get().to(introspection_handler)),
)
})
.workers(3)
.bind("127.0.0.1:8082")?
.run();
future::try_join(srv1, srv2).await?;
}
#[cfg(not(feature = "experimental-introspection"))]
{
eprintln!("This example requ... |
rust_dataset_chunk_740 | rust_dataset.txt | 740 | 512 | async fn introspection_handler_text(
tree: web::Data<actix_web::introspection::IntrospectionTree>,
) -> impl Responder {
let report = tree.report_as_text();
HttpResponse::Ok().content_type("text/plain").body(report)
}
// GET /api/v1/item/{id} and GET ... |
rust_dataset_chunk_741 | rust_dataset.txt | 741 | 512 | !")
}
// Additional endpoints for /extra
fn extra_endpoints(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/extra")
.route(
"/ping",
web::get().to(|| async { HttpResponse::Ok().body("pong")... |
rust_dataset_chunk_742 | rust_dataset.txt | 742 | 512 |
// curl --location '127.0.0.1:8080/introspection' --header 'Accept: application/json'
// curl --location '127.0.0.1:8080/introspection' --header 'Accept: text/plain'
// curl --location '127.0.0.1:8080/introspection/externals'
.external_resource("app-exter... |
rust_dataset_chunk_743 | rust_dataset.txt | 743 | 512 | 1 (outside /api)
.service(web::scope("/v1").service(get_item)) // GET /v1/item/{id}
// Admin endpoints under /admin
.service(
web::scope("/admin")
.route("/dashboard", web::get().to(admin_dashboard)) // GET /admin/dashboard
... |
rust_dataset_chunk_744 | rust_dataset.txt | 744 | 512 | HttpServer};
async fn index(req: HttpRequest) -> &'static str {
println!("REQ: {:?}", req);
"Hello world!\r\n"
}
fn main() -> std::io::Result<()> {
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
rt::System::new().block_on(
HttpServer::new(|| {
App::n... |
rust_dataset_chunk_745 | rust_dataset.txt | 745 | 512 | await?;
Ok(res.map_body(move |_, _| string_body))
}
async fn timeout_10secs(
req: ServiceRequest,
next: Next<impl MessageBody + 'static>,
) -> Result<ServiceResponse<impl MessageBody>, Error> {
match tokio::time::timeout(Duration::from_secs(10), next.call(req)).await {
Ok(res) => res,
... |
rust_dataset_chunk_746 | rust_dataset.txt | 746 | 512 | .wrap(MyMw(false).into_middleware())
.wrap(Logger::default())
.default_service(web::to(HttpResponse::Ok))
})
.workers(1)
.bind(bind)?
.run()
.await
}
--- FILE: actix-web/actix-web/examples/on-connect.rs ---
//! This example shows how to use `actix_web::HttpServe... |
rust_dataset_chunk_747 | rust_dataset.txt | 747 | 512 | await
}
--- FILE: actix-web/actix-web/examples/query.rs ---
use std::io;
use actix_web::{get, query, web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize)]
struct SearchQuery {
user_id: u64,
status: String,
}
#[derive(Debug, Serialize)]
struct Sea... |
rust_dataset_chunk_748 | rust_dataset.txt | 748 | 512 | ();
let url = format!("http://{addr}/");
// The socket is bound, but the server cannot respond before its first poll.
println!("Sending a request before startup; expecting a timeout...");
let err = timeout(Duration::from_secs(2), client.get(&url).send())
.await
.unwrap_err();
printl... |
rust_dataset_chunk_749 | rust_dataset.txt | 749 | 512 | )
.service(
web::resource("/resource2/index.html")
.wrap(middleware::DefaultHeaders::new().add(("X-Version-R2", "0.3")))
.default_service(web::route().to(HttpResponse::MethodNotAllowed))
.route(web::get().to(index_async)),
... |
rust_dataset_chunk_750 | rust_dataset.txt | 750 | 512 | app_service::{AppEntry, AppInit, AppRoutingFactory},
config::ServiceConfig,
data::{Data, DataFactory, FnDataFactory},
dev::ResourceDef,
error::Error,
resource::Resource,
route::Route,
service::{
AppServiceFactory, BoxedHttpServiceFactory, HttpServiceFactory, ServiceFactoryWrapper... |
rust_dataset_chunk_751 | rust_dataset.txt | 751 | 512 | 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 n... |
rust_dataset_chunk_752 | rust_dataset.txt | 752 | 512 | "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 ser... |
rust_dataset_chunk_753 | rust_dataset.txt | 753 | 512 | 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.
... |
rust_dataset_chunk_754 | rust_dataset.txt | 754 | 512 | ").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 ... |
rust_dataset_chunk_755 | rust_dataset.txt | 755 | 512 | 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
/// ``... |
rust_dataset_chunk_756 | rust_dataset.txt | 756 | 512 | _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?;
/... |
rust_dataset_chunk_757 | rust_dataset.txt | 757 | 512 | ")]
introspector: Rc::clone(&self.introspector),
}
}
}
#[cfg(test)]
mod tests {
use std::future::ready;
use actix_service::Service as _;
use bytes::Bytes;
use super::*;
use crate::{
http::{
header::{self, HeaderValue},
Method, StatusCode,
... |
rust_dataset_chunk_758 | rust_dataset.txt | 758 | 512 | ::new()
.data_factory(|| ready(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.statu... |
rust_dataset_chunk_759 | rust_dataset.txt | 759 | 512 | resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
}
#[tokio::test(flavor = "local")]
async fn test_router_wrap() {
let srv = init_service(
App::new()
.route("/test", web::get().to(HttpResponse::Ok))
... |
rust_dataset_chunk_760 | rust_dataset.txt | 760 | 512 | OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),
HeaderValue::from_static("0001")
);
}
#[tokio::test(flavor = "local")]
async fn test_external_resource() {
let srv = init_service(
App::new()
.external_resource("y... |
rust_dataset_chunk_761 | rust_dataset.txt | 761 | 512 | ServiceResponse,
},
Error, HttpMessage as _, 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>... |
rust_dataset_chunk_762 | rust_dataset.txt | 762 | 512 | AppService::new(config, Rc::clone(&default));
#[cfg(feature = "experimental-introspection")]
{
config.introspector = Rc::clone(&self.introspector);
}
// register services
mem::take(&mut *self.services.borrow_mut())
.into_iter()
.for_each(|mut... |
rust_dataset_chunk_763 | rust_dataset.txt | 763 | 512 | populate app data container from (async) data factories.
for factory in &async_data_factories {
factory.create(&mut app_data);
}
#[cfg(feature = "experimental-introspection")]
{
let tree = introspector.borrow_mut().finalize();
... |
rust_dataset_chunk_764 | rust_dataset.txt | 764 | 512 | , 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... |
rust_dataset_chunk_765 | rust_dataset.txt | 765 | 512 | ().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 defa... |
rust_dataset_chunk_766 | rust_dataset.txt | 766 | 512 | 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 c... |
rust_dataset_chunk_767 | rust_dataset.txt | 767 | 512 | } else {
cfg.service(get_items).service(post_items);
}
});
let app = init_service(app).await;
let path = if scoped { "/api/items" } else { "/items" };
for methods in [
... |
rust_dataset_chunk_768 | rust_dataset.txt | 768 | 512 | data::Data,
dev::{Extensions, ResourceDef},
error::Error,
guard::Guard,
resource::Resource,
rmap::ResourceMap,
route::Route,
service::{
AppServiceFactory, BoxedHttpServiceFactory, HttpServiceFactory, ServiceFactoryWrapper,
ServiceRequest, ServiceResponse,
},
};
type ... |
rust_dataset_chunk_769 | rust_dataset.txt | 769 | 512 | )>,
std::rc::Rc<std::cell::RefCell<crate::introspection::IntrospectionCollector>>,
) {
(self.config, self.services, self.introspector)
}
#[allow(clippy::type_complexity)]
#[cfg(not(feature = "experimental-introspection"))]
pub(crate) fn into_services(
self,
) -> (
... |
rust_dataset_chunk_770 | rust_dataset.txt | 770 | 512 | [], |v| &v[..]);
let methods = guard_list
.iter()
.flat_map(|g| g.details().unwrap_or_default())
.flat_map(|d| {
if let crate::guard::GuardDetail::HttpMethods(v) = d {
v.into_iter()
.filte... |
rust_dataset_chunk_771 | rust_dataset.txt | 771 | 512 | fn prepare_scope_id(&mut self) -> usize {
let scope_id = self.introspector.borrow_mut().next_scope_id();
self.pending_scope_id = Some(scope_id);
scope_id
}
}
/// Application connection config.
#[derive(Debug, Clone)]
pub struct AppConfig {
secure: bool,
host: String,
addr: Sock... |
rust_dataset_chunk_772 | rust_dataset.txt | 772 | 512 | 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.
///
/// Mer... |
rust_dataset_chunk_773 | rust_dataset.txt | 773 | 512 | , 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... |
rust_dataset_chunk_774 | rust_dataset.txt | 774 | 512 |
}
}
#[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 deprecate... |
rust_dataset_chunk_775 | rust_dataset.txt | 775 | 512 | 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!(... |
rust_dataset_chunk_776 | rust_dataset.txt | 776 | 512 | .rs ---
use std::{any::type_name, ops::Deref, sync::Arc};
use actix_http::Extensions;
#[expect(deprecated, reason = "preserve the public ready future type")]
use actix_utils::future::{ready, Ready};
use futures_core::future::LocalBoxFuture;
use serde::{de, Serialize};
use crate::{dev::Payload, error, Error, FromReque... |
rust_dataset_chunk_777 | rust_dataset.txt | 777 | 512 | 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)... |
rust_dataset_chunk_778 | rust_dataset.txt | 778 | 512 | -> 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 ... |
rust_dataset_chunk_779 | rust_dataset.txt | 779 | 512 | 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_serv... |
rust_dataset_chunk_780 | rust_dataset.txt | 780 | 512 | (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()
... |
rust_dataset_chunk_781 | rust_dataset.txt | 781 | 512 | #[tokio::test(flavor = "local")]
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);
}
#[tokio::test(flavor = "local")]
async fn test_dat... |
rust_dataset_chunk_782 | rust_dataset.txt | 782 | 512 | //! 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
//! - [`... |
rust_dataset_chunk_783 | rust_dataset.txt | 783 | 512 | <dyn ResponseError>,
response_mappers: Vec<Box<dyn Fn(HttpResponse) -> HttpResponse>>,
}
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.... |
rust_dataset_chunk_784 | rust_dataset.txt | 784 | 512 | made by earlier mappers:
///
/// ```
/// use actix_web::{error, HttpResponse};
///
/// let mut err = error::ErrorBadRequest("bad request");
/// err.add_response_mapper(|_| HttpResponse::InternalServerError().finish());
/// ```
pub fn add_response_mapper<F>(&mut self, mapper: F)
wher... |
rust_dataset_chunk_785 | rust_dataset.txt | 785 | 512 | 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,
statu... |
rust_dataset_chunk_786 | rust_dataset.txt | 786 | 512 | , 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_... |
rust_dataset_chunk_787 | rust_dataset.txt | 787 | 512 | _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... |
rust_dataset_chunk_788 | rust_dataset.txt | 788 | 512 | 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::... |
rust_dataset_chunk_789 | rust_dataset.txt | 789 | 512 | Large("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"... |
rust_dataset_chunk_790 | rust_dataset.txt | 790 | 512 | 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 `... |
rust_dataset_chunk_791 | rust_dataset.txt | 791 | 512 | _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)) }
} ... |
rust_dataset_chunk_792 | rust_dataset.txt | 792 | 512 | Error};
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 runn... |
rust_dataset_chunk_793 | rust_dataset.txt | 793 | 512 | ("Error that occur during reading payload: {}", _0)]
Payload(PayloadError),
}
impl ResponseError for UrlencodedError {
fn status_code(&self) -> StatusCode {
match self {
Self::Overflow { .. } | Self::OverflowUnknownLength { .. } => {
StatusCode::PAYLOAD_TOO_LARGE
... |
rust_dataset_chunk_794 | rust_dataset.txt | 794 | 512 | 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... |
rust_dataset_chunk_795 | rust_dataset.txt | 795 | 512 | 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... |
rust_dataset_chunk_796 | rust_dataset.txt | 796 | 512 | 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 {
... |
rust_dataset_chunk_797 | rust_dataset.txt | 797 | 512 | (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... |
rust_dataset_chunk_798 | rust_dataset.txt | 798 | 512 | | [`PathConfig`] |
/// | [`Json`] | [`JsonConfig`] |
/// | [`Form`] | [`FormConfig`] |
/// | [`Query`] | [`QueryConfig`] |
/// | [`Bytes`] | [`PayloadConfig`] |
/// | [`String`] | [`PayloadConfig`] |
/// | [`Payload`] | [`PayloadConfig`] |
///
/// # Implementing An Extractor
/// To reduce duplica... |
rust_dataset_chunk_799 | rust_dataset.txt | 799 | 512 | <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)`.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.