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_1000
rust_dataset.txt
1,000
512
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...
rust_dataset_chunk_1001
rust_dataset.txt
1,001
512
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 Tempor...
rust_dataset_chunk_1002
rust_dataset.txt
1,002
512
.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_cod...
rust_dataset_chunk_1003
rust_dataset.txt
1,003
512
_u16(307).unwrap()); let hdr = res.headers().get(&LOCATION).unwrap(); assert_eq!(hdr.to_str().unwrap(), "https://duck.com"); } #[tokio::test(flavor = "local")] async fn as_responder() { let responder = Redirect::to("https://duck.com"); let req = test::TestRequest::default()...
rust_dataset_chunk_1004
rust_dataset.txt
1,004
512
: 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...
rust_dataset_chunk_1005
rust_dataset.txt
1,005
512
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 ...
rust_dataset_chunk_1006
rust_dataset.txt
1,006
512
ix_http::{Message, RequestHead}; use actix_router::{Path, Url}; #[expect(deprecated, reason = "preserve the public ready future type")] use actix_utils::future::{ready, Ready}; #[cfg(feature = "cookies")] use cookie::{Cookie, ParseError as CookieParseError}; use smallvec::SmallVec; use crate::{ app_service::AppIni...
rust_dataset_chunk_1007
rust_dataset.txt
1,007
512
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 reques...
rust_dataset_chunk_1008
rust_dataset.txt
1,008
512
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 { ...
rust_dataset_chunk_1009
rust_dataset.txt
1,009
512
/// 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 ...
rust_dataset_chunk_1010
rust_dataset.txt
1,010
512
, 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}/...
rust_dataset_chunk_1011
rust_dataset.txt
1,011
512
, { self.resource_map().url_for_map(self, name, elements) } /// Generates URL for a named resource using an iterator of key-value pairs. /// /// This is a convenience wrapper around [`HttpRequest::url_for_map`]. /// /// Note: passing a borrowed map (e.g. `&HashMap<String, String>`) ...
rust_dataset_chunk_1012
rust_dataset.txt
1,012
512
'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 ...
rust_dataset_chunk_1013
rust_dataset.txt
1,013
512
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. /// /// #...
rust_dataset_chunk_1014
rust_dataset.txt
1,014
512
} /// Load request cookies **without** percent-decoding their names and values. /// /// Any cookie that cannot be parsed is omitted from the result. /// This includes cookies with an empty name (e.g. `document.cookie = "=value"`). #[cfg(feature = "cookies")] pub fn cookies_raw(&self) -> Res...
rust_dataset_chunk_1015
rust_dataset.txt
1,015
512
::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 s...
rust_dataset_chunk_1016
rust_dataset.txt
1,016
512
?}", 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 fro...
rust_dataset_chunk_1017
rust_dataset.txt
1,017
512
push(&self, req: Rc<HttpRequestInner>) { self.inner.borrow_mut().push(req); } /// Prevents future requests from being returned to the pool and clears existing entries. pub(crate) fn disable(&self) { self.enabled.set(false); self.inner.borrow_mut().clear(); } } #[cfg(test)] mod...
rust_dataset_chunk_1018
rust_dataset.txt
1,018
512
"cookie2=%db")) .to_http_request(); { let cookies = req.cookies_raw().unwrap(); assert_eq!(cookies.len(), 2); assert_eq!(cookies[0].name(), "cookie1"); assert_eq!(cookies[0].value(), "hello%20world"); assert_eq!(cookies[1].name(), "cookie2...
rust_dataset_chunk_1019
rust_dataset.txt
1,019
512
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) ...
rust_dataset_chunk_1020
rust_dataset.txt
1,020
512
().as_str(), "http://www.actix.rs/user/test.html" ); let url = req.url_for_iter("index", [("name", "test")]); assert_eq!(url, Err(UrlGenerationError::NotEnoughElements)); } #[test] fn test_url_for_static() { let mut rdef = ResourceDef::new("/index.html"); ...
rust_dataset_chunk_1021
rust_dataset.txt
1,021
512
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...
rust_dataset_chunk_1022
rust_dataset.txt
1,022
512
.await; let req = TestRequest::default().to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } #[tokio::test(flavor = "local")] async fn test_cascading_data() { #[allow(dead_code)] fn echo_usize(req: Ht...
rust_dataset_chunk_1023
rust_dataset.txt
1,023
512
= read_body(resp).await; assert_eq!(body, Bytes::from_static(b"1")); } #[tokio::test(flavor = "local")] async fn test_app_data_dropped() { struct Tracker { pub dropped: bool, } struct Foo { tracker: Rc<RefCell<Tracker>>, } impl Drop f...
rust_dataset_chunk_1024
rust_dataset.txt
1,024
512
web::scope("/widgets") .service( web::resource("/{id}") .name("get_widget") .guard(guard::Get()) .to(|req: HttpRequest| { assert_eq!(req.match_pattern(), Some(...
rust_dataset_chunk_1025
rust_dataset.txt
1,025
512
("/not-exist").to_request(); let res = call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); } #[tokio::test(flavor = "local")] async fn url_for_closest_named_resource() { // we mount the route named 'nested' on 2 different scopes, 'a' and 'b' let srv = te...
rust_dataset_chunk_1026
rust_dataset.txt
1,026
512
((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 = TestReq...
rust_dataset_chunk_1027
rust_dataset.txt
1,027
512
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, AppSer...
rust_dataset_chunk_1028
rust_dataset.txt
1,028
512
_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, defaul...
rust_dataset_chunk_1029
rust_dataset.txt
1,029
512
::{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(|| Htt...
rust_dataset_chunk_1030
rust_dataset.txt
1,030
512
/// 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)) //...
rust_dataset_chunk_1031
rust_dataset.txt
1,031
512
js terminology pub fn wrap<M, B>( self, mw: M, ) -> Resource< impl ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error = Error, InitError = (), >, > where M: Transform< ...
rust_dataset_chunk_1032
rust_dataset.txt
1,032
512
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)) ///...
rust_dataset_chunk_1033
rust_dataset.txt
1,033
512
delete, "DELETE"); route_shortcut!(query, "QUERY"); route_shortcut!(head, "HEAD"); route_shortcut!(trace, "TRACE"); } impl<T, B> HttpServiceFactory for Resource<T> where T: ServiceFactory< ServiceRequest, Config = (), Response = ServiceResponse<B>, Error ...
rust_dataset_chunk_1034
rust_dataset.txt
1,034
512
_reports_from_iter( resource_guards.iter().chain(route_guards.iter()), ); for full_path in &full_paths { let info = crate::introspection::RouteInfo::new( full_path.clone(), methods.clone(), ...
rust_dataset_chunk_1035
rust_dataset.txt
1,035
512
= 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.de...
rust_dataset_chunk_1036
rust_dataset.txt
1,036
512
service(my_resource_3()); } #[tokio::test(flavor = "local")] async fn test_middleware() { let srv = init_service( App::new().service( web::resource("/test") .name("test") .wrap( DefaultHeaders::new() ...
rust_dataset_chunk_1037
rust_dataset.txt
1,037
512
::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("/te...
rust_dataset_chunk_1038
rust_dataset.txt
1,038
512
_service( App::new() .service( web::resource("/test/{p}") .guard(guard::Get()) .to(HttpResponse::Ok), ) .service( web::resource("/test/{p}") .guard(...
rust_dataset_chunk_1039
rust_dataset.txt
1,039
512
_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::D...
rust_dataset_chunk_1040
rust_dataset.txt
1,040
512
req.extensions().get::<usize>(), Some(&1)); Ok(ServiceResponse::new( req, HttpResponse::BadRequest().finish(), )) }), ), ) .await; let req = TestRequest::get(...
rust_dataset_chunk_1041
rust_dataset.txt
1,041
512
#[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: StatusC...
rust_dataset_chunk_1042
rust_dataset.txt
1,042
512
: 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_heade...
rust_dataset_chunk_1043
rust_dataset.txt
1,043
512
} 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...
rust_dataset_chunk_1044
rust_dataset.txt
1,044
512
/// .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(...
rust_dataset_chunk_1045
rust_dataset.txt
1,045
512
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, ...
rust_dataset_chunk_1046
rust_dataset.txt
1,046
512
{ 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: Ht...
rust_dataset_chunk_1047
rust_dataset.txt
1,047
512
, 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 ...
rust_dataset_chunk_1048
rust_dataset.txt
1,048
512
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_...
rust_dataset_chunk_1049
rust_dataset.txt
1,049
512
inner.status = Some(status); } self } /// Insert (override) header in the final response. /// /// Overrides other headers with the same name. /// See [`HeaderMap::insert`](crate::http::header::HeaderMap::insert). /// /// Headers added with this method will be inserted befo...
rust_dataset_chunk_1050
rust_dataset.txt
1,050
512
.inner() { match header.try_into_pair() { Ok((key, value)) => { inner.append_headers.append(key, value); } Err(err) => self.error = Some(err.into()), }; } self } #[doc(hidden)] #[deprecated(since = ...
rust_dataset_chunk_1051
rust_dataset.txt
1,051
512
use crate::{ cookie::Cookie, http::header::{HeaderValue, CONTENT_TYPE}, test::TestRequest, }; #[tokio::test(flavor = "local")] async fn customize_responder() { let req = TestRequest::default().to_http_request(); let res = "test" .to_string() ...
rust_dataset_chunk_1052
rust_dataset.txt
1,052
512
assert_eq!( to_bytes(res.into_body()).await.unwrap(), Bytes::from_static(b"test"), ); } } --- FILE: actix-web/actix-web/src/response/http_codes.rs --- //! Status code based HTTP response builders. use actix_http::StatusCode; use crate::{HttpResponse, HttpResponseBuilder};...
rust_dataset_chunk_1053
rust_dataset.txt
1,053
512
StatusCode::PROXY_AUTHENTICATION_REQUIRED ); static_resp!(RequestTimeout, StatusCode::REQUEST_TIMEOUT); static_resp!(Conflict, StatusCode::CONFLICT); static_resp!(Gone, StatusCode::GONE); static_resp!(LengthRequired, StatusCode::LENGTH_REQUIRED); static_resp!(PreconditionFailed, StatusCode::PRE...
rust_dataset_chunk_1054
rust_dataset.txt
1,054
512
assert_eq!(resp.status(), StatusCode::OK); } } --- FILE: actix-web/actix-web/src/response/mod.rs --- mod builder; mod customize_responder; mod http_codes; mod responder; #[allow(clippy::module_inception)] mod response; pub use self::{ builder::HttpResponseBuilder, customize_responder::CustomizeRespon...
rust_dataset_chunk_1055
rust_dataset.txt
1,055
512
implemented `Responder` where appropriate. For example, /// HTML templating engines. /// /// # Customizing Responder Output /// Calling [`.customize()`](Responder::customize) on any responder type will wrap it in a /// [`CustomizeResponder`] capable of overriding various parts of the response such as the status /// ...
rust_dataset_chunk_1056
rust_dataset.txt
1,056
512
Body = BoxBody; #[inline] fn respond_to(mut self, req: &HttpRequest) -> HttpResponse<Self::Body> { self.finish().map_into_boxed_body().respond_to(req) } } impl<R: Responder> Responder for Option<R> { type Body = EitherBody<R::Body>; fn respond_to(self, req: &HttpRequest) -> HttpResponse<...
rust_dataset_chunk_1057
rust_dataset.txt
1,057
512
self.into(); res.into() } } }; ($res:ty) => { impl_responder_by_forward_into_base_response!($res, $res); }; } impl_responder_by_forward_into_base_response!(&'static [u8]); impl_responder_by_forward_into_base_response!(Vec<u8>); impl_responder_by_forward_into_ba...
rust_dataset_chunk_1058
rust_dataset.txt
1,058
512
"test".respond_to(&req); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("text/plain; charset=utf-8") ); assert_eq!( to_bytes(res.into_body()).await.unwrap(), Bytes::...
rust_dataset_chunk_1059
rust_dataset.txt
1,059
512
test").respond_to(&req); assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(CONTENT_TYPE).unwrap(), HeaderValue::from_static("text/plain; charset=utf-8") ); assert_eq!( to_bytes(res.into_body()).await.unwrap(), Bytes::f...
rust_dataset_chunk_1060
rust_dataset.txt
1,060
512
Response, ResponseHead, StatusCode, }; #[cfg(feature = "cookies")] use { actix_http::{ error::HttpError, header::{self, HeaderValue}, }, cookie::Cookie, }; use crate::{error::Error, HttpRequest, HttpResponseBuilder, Responder}; /// An outgoing response. pub struct HttpResponse<B = BoxBody...
rust_dataset_chunk_1061
rust_dataset.txt
1,061
512
) -> &mut HeaderMap { self.res.headers_mut() } /// Get an iterator for the cookies set by this response. #[cfg(feature = "cookies")] pub fn cookies(&self) -> CookieIter<'_> { CookieIter { iter: self.headers().get_all(header::SET_COOKIE), } } /// Add a cookie...
rust_dataset_chunk_1062
rust_dataset.txt
1,062
512
[`add_removal_cookie`]. Use [`add_removal_cookie`] to send a "removal" cookie. /// /// [`add_cookie`]: Self::add_cookie /// [`add_removal_cookie`]: Self::add_removal_cookie #[cfg(feature = "cookies")] pub fn del_cookie(&mut self, name: &str) -> usize { let headers = self.headers_mut(); ...
rust_dataset_chunk_1063
rust_dataset.txt
1,063
512
B) { let (head, body) = self.res.into_parts(); ( HttpResponse { res: head, error: self.error, }, body, ) } /// Drops body and returns new response. pub fn drop_body(self) -> HttpResponse<()> { HttpResponse...
rust_dataset_chunk_1064
rust_dataset.txt
1,064
512
Response<B>) -> Self { HttpResponse { res, error: None } } } impl From<Error> for HttpResponse { fn from(err: Error) -> Self { HttpResponse::from_error(err) } } impl<B> From<HttpResponse<B>> for Response<B> { fn from(res: HttpResponse<B>) -> Self { // this impl will always be ...
rust_dataset_chunk_1065
rust_dataset.txt
1,065
512
.iter.by_ref() { if let Ok(c) = Cookie::parse_encoded(v.to_str().ok()?) { return Some(c); } } None } } #[cfg(test)] mod tests { use static_assertions::assert_impl_all; use super::*; use crate::http::header::COOKIE; assert_impl_all!(HttpRespo...
rust_dataset_chunk_1066
rust_dataset.txt
1,066
512
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: RefCe...
rust_dataset_chunk_1067
rust_dataset.txt
1,067
512
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().unw...
rust_dataset_chunk_1068
rust_dataset.txt
1,068
512
Elements)?; self.url_from_path(req, path) } /// Generate URL for named resource using an iterator of key-value pairs. /// /// Check [`HttpRequest::url_for_iter`] for detailed information. pub fn url_for_iter<K, V, I>( &self, req: &HttpRequest, name: &str, el...
rust_dataset_chunk_1069
rust_dataset.txt
1,069
512
) -> 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) }, ) } pub(crate)...
rust_dataset_chunk_1070
rust_dataset.txt
1,070
512
_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) -> ...
rust_dataset_chunk_1071
rust_dataset.txt
1,071
512
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("/...
rust_dataset_chunk_1072
rust_dataset.txt
1,072
512
!(!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").i...
rust_dataset_chunk_1073
rust_dataset.txt
1,073
512
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"), Non...
rust_dataset_chunk_1074
rust_dataset.txt
1,074
512
("")); 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...
rust_dataset_chunk_1075
rust_dataset.txt
1,075
512
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] ...
rust_dataset_chunk_1076
rust_dataset.txt
1,076
512
. If handler is not set, a `404 Not Found` /// handler is used. pub struct Route { service: BoxedHttpServiceFactory, guards: Rc<Vec<Box<dyn Guard>>>, wrapped: bool, } impl Route { /// Create new route which matches any request. #[allow(clippy::new_without_default)] pub fn new() -> Route { ...
rust_dataset_chunk_1077
rust_dataset.txt
1,077
512
()` now would replace the wrapped service and silently drop middleware. \ Call `.{replaced}()` before `.wrap()` (for example: `{example}`)." ); } } impl ServiceFactory<ServiceRequest> for Route { type Response = ServiceResponse; type Error = Error; type Config = (); type Servic...
rust_dataset_chunk_1078
rust_dataset.txt
1,078
512
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/p...
rust_dataset_chunk_1079
rust_dataset.txt
1,079
512
( /// web::resource("/{username}/index.html") // <- define path parameters /// .route(web::get().to(index)) /// ); /// ``` /// /// # Panics /// Panics if called after [`Route::wrap`], since this would replace the wrapped service and /// silently discard middleware. #[trac...
rust_dataset_chunk_1080
rust_dataset.txt
1,080
512
, Response = ServiceResponse, Error = E, InitError = (), Config = (), > + 'static, E: Into<Error> + 'static, { if self.wrapped { Self::panic_after_wrap("service", "web::get().service(factory).wrap(mw)"); ...
rust_dataset_chunk_1081
rust_dataset.txt
1,081
512
("/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(&...
rust_dataset_chunk_1082
rust_dataset.txt
1,082
512
); 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); } #[tokio::test(flavor = "local")] async fn test_service_hand...
rust_dataset_chunk_1083
rust_dataset.txt
1,083
512
was already registered with `.wrap()`")] fn wrap_before_to_panics() { web::get() .wrap(DefaultHeaders::new().add(("x-test", "x-value"))) .to(HttpResponse::Ok); } #[test] #[should_panic(expected = "Route middleware was already registered with `.wrap()`")] fn wrap_bef...
rust_dataset_chunk_1084
rust_dataset.txt
1,084
512
(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 in...
rust_dataset_chunk_1085
rust_dataset.txt
1,085
512
::{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::LocalBoxFut...
rust_dataset_chunk_1086
rust_dataset.txt
1,086
512
]: 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>, fac...
rust_dataset_chunk_1087
rust_dataset.txt
1,087
512
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...
rust_dataset_chunk_1088
rust_dataset.txt
1,088
512
::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), { ...
rust_dataset_chunk_1089
rust_dataset.txt
1,089
512
/// 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( ...
rust_dataset_chunk_1090
rust_dataset.txt
1,090
512
_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 ...
rust_dataset_chunk_1091
rust_dataset.txt
1,091
512
ResourceMap::new(ResourceDef::root_prefix(&self.rdef)); #[cfg(feature = "experimental-introspection")] let origin_scope = cfg.current_prefix.clone(); // external resources for mut rdef in mem::take(&mut self.external) { #[cfg(feature = "experimental-introspection")] ...
rust_dataset_chunk_1092
rust_dataset.txt
1,092
512
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, gu...
rust_dataset_chunk_1093
rust_dataset.txt
1,093
512
} 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, _: ()) -> ...
rust_dataset_chunk_1094
rust_dataset.txt
1,094
512
test(flavor = "local")] 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)), ), ...
rust_dataset_chunk_1095
rust_dataset.txt
1,095
512
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(); ...
rust_dataset_chunk_1096
rust_dataset.txt
1,096
512
to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::OK); } #[tokio::test(flavor = "local")] async fn test_scope_variable_segment() { let srv = init_service(App::new().service(web::scope("/ab-{project}").service( web::resource("/pa...
rust_dataset_chunk_1097
rust_dataset.txt
1,097
512
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();...
rust_dataset_chunk_1098
rust_dataset.txt
1,098
512
(|r: HttpRequest| { HttpResponse::Created().body(format!( "project: {} - {}", &r.match_info()["project"], &r.match_info()["id"], )) }), )), ))) .await; let...
rust_dataset_chunk_1099
rust_dataset.txt
1,099
512
with_uri("/app2/non-exist").to_request(); let resp = srv.call(req).await.unwrap(); assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); } #[tokio::test(flavor = "local")] async fn test_middleware() { let srv = init_service( App::new().service( web::...