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_900
rust_dataset.txt
900
512
those header types. #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Hash)] pub enum Preference<T> { /// A wildcard value. Any, /// A valid `T`. Specific(T), } impl<T> Preference<T> { /// Returns true if preference is the any/wildcard (`*`) value. pub fn is_any(&self) -> bool { ...
rust_dataset_chunk_901
rust_dataset.txt
901
512
.1) /// /// The "Range" header field on a GET request modifies the method semantics to request transfer of /// only one or more sub-ranges of the selected representation data, rather than the entire selected /// representation data. /// /// # Note /// This is a request header. Servers should not send `Range` in respons...
rust_dataset_chunk_902
rust_dataset.txt
902
512
/// (`other-range-unit`: String , `other-range-set`: String) Unregistered(String, String), } /// A range of bytes to fetch. /// /// Each [`Range::Bytes`] header can contain one or more `ByteRangeSpec`s. #[derive(Debug, Clone, PartialEq, Eq)] pub enum ByteRangeSpec { /// All bytes from `x` to `y`, inclusive...
rust_dataset_chunk_903
rust_dataset.txt
903
512
unsatisfiable. /// /// The function also computes remainder ranges based on the RFC: /// /// > If the last-byte-pos value is absent, or if the value is greater than or equal to the /// > current length of the representation data, the byte range is interpreted as the remainder /// > of the repre...
rust_dataset_chunk_904
rust_dataset.txt
904
512
.map(|(from, to)| ByteRangeSpec::FromTo(from, to)) .collect(), ) } } impl fmt::Display for ByteRangeSpec { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { ByteRangeSpec::FromTo(from, to) => write!(f, "{}-{}", from, to), ...
rust_dataset_chunk_905
rust_dataset.txt
905
512
parse() .or(Err(ParseError::Header)) .map(ByteRangeSpec::From), (start, end) => match (start.parse(), end.parse()) { (Ok(start), Ok(end)) if start <= end => Ok(ByteRangeSpec::FromTo(start, end)), _ => Err(ParseError::Header), }, ...
rust_dataset_chunk_906
rust_dataset.txt
906
512
::FromTo(1, 100), ByteRangeSpec::From(200), ]); assert_eq!(r, r2); assert_eq!(r2, r3); let r: Range = Header::parse(&req("bytes=1-100,-100")).unwrap(); let r2: Range = Header::parse(&req("bytes=1-100, ,,-100")).unwrap(); let r3 = Range::Bytes(vec![ ...
rust_dataset_chunk_907
rust_dataset.txt
907
512
let r: Result<Range, ParseError> = Header::parse(&req("bytes=")); assert_eq!(r.ok(), None); let r: Result<Range, ParseError> = Header::parse(&req("custom=")); assert_eq!(r.ok(), None); let r: Result<Range, ParseError> = Header::parse(&req("=1-100")); assert_eq!(r.ok(), None); ...
rust_dataset_chunk_908
rust_dataset.txt
908
512
).to_satisfiable_range(3)); assert_eq!(None, ByteRangeSpec::From(0).to_satisfiable_range(0)); assert_eq!(Some((1, 2)), ByteRangeSpec::Last(2).to_satisfiable_range(3)); assert_eq!(Some((2, 2)), ByteRangeSpec::Last(1).to_satisfiable_range(3)); assert_eq!(Some((0, 2)), ByteRangeSpec::Last(...
rust_dataset_chunk_909
rust_dataset.txt
909
512
} else { val.split(':').next().unwrap_or(val) } } /// Extracts and trims first value for given header name. fn first_header_value<'a>(req: &'a RequestHead, name: &'_ HeaderName) -> Option<&'a str> { let hdr = req.headers.get(name)?.to_str().ok()?; let val = hdr.split(',').next()?.trim(); Some(...
rust_dataset_chunk_910
rust_dataset.txt
910
512
mut scheme = None; let mut realip_remote_addr = None; for (name, val) in req .headers .get_all(&header::FORWARDED) .filter_map(|hdr| hdr.to_str().ok()) // "for=1.2.3.4, for=5.6.7.8; scheme=https" .flat_map(|val| val.split(';')) //...
rust_dataset_chunk_911
rust_dataset.txt
911
512
_or("http") .to_owned(); let host = host .or_else(|| first_header_value(req, &X_FORWARDED_HOST)) .or_else(|| req.headers.get(&header::HOST)?.to_str().ok()) .or_else(|| req.uri.authority().map(Authority::as_str)) .unwrap_or_else(|| cfg.host()) ...
rust_dataset_chunk_912
rust_dataset.txt
912
512
following, in order: /// - `Forwarded` header /// - `X-Forwarded-Proto` header /// - request target / URI #[inline] pub fn scheme(&self) -> &str { &self.scheme } #[doc(hidden)] #[deprecated(since = "4.0.0", note = "Renamed to `peer_addr`.")] pub fn remote_addr(&self) -> Opt...
rust_dataset_chunk_913
rust_dataset.txt
913
512
mod tests { use super::*; use crate::test::TestRequest; const X_FORWARDED_FOR: &str = "x-forwarded-for"; const X_FORWARDED_HOST: &str = "x-forwarded-host"; const X_FORWARDED_PROTO: &str = "x-forwarded-proto"; #[test] fn info_default() { let req = TestRequest::default().to_http_requ...
rust_dataset_chunk_914
rust_dataset.txt
914
512
https"); assert_eq!(info.host(), "rust-lang.org"); assert_eq!(info.realip_remote_addr(), Some("192.0.2.60")); let req = TestRequest::default() .insert_header(( header::FORWARDED, "for=192.0.2.60; proto=https; by=203.0.113.43; host=rust-lang.org", ...
rust_dataset_chunk_915
rust_dataset.txt
915
512
]""#)) .to_http_request(); let info = req.connection_info(); assert_eq!(info.realip_remote_addr(), Some("2001:db8:cafe::17")); } #[test] fn forwarded_for_ipv6_with_port() { let req = TestRequest::default() .insert_header((header::FORWARDED, r#"for="[2001:db8:...
rust_dataset_chunk_916
rust_dataset.txt
916
512
_extract() { let req = TestRequest::default().to_http_request(); let res = PeerAddr::extract(&req).await; assert!(res.is_err()); let addr = "127.0.0.1:8080".parse().unwrap(); let req = TestRequest::default().peer_addr(addr).to_http_request(); let peer_addr = PeerAddr::ex...
rust_dataset_chunk_917
rust_dataset.txt
917
512
are best-effort and derived only from explicit method guards; an empty list means //! no explicit method guards were observed for the node. //! - Guard and method lists are aggregated per `full_path` and do not preserve per-route //! correlations when multiple routes/services share the same path. //! - Reachabilit...
rust_dataset_chunk_918
rust_dataset.txt
918
512
String, pub value: String, } /// A report item for an external resource configured for URL generation. /// /// `origin_scope` is the scope path where the external resource was registered. It is informational /// only and does not affect URL generation or routing; external resources are always global. #[non_exhaus...
rust_dataset_chunk_919
rust_dataset.txt
919
512
unreachable at runtime. pub potentially_unreachable: bool, /// Reasons for potential unreachability. pub reachability_notes: Vec<String>, } /// A flattened report item for a route. #[non_exhaustive] #[derive(Debug, Clone, Serialize)] pub struct IntrospectionReportItem { /// Full path for the route. ...
rust_dataset_chunk_920
rust_dataset.txt
920
512
(), children: Vec::new(), potentially_unreachable: false, reachability_notes: Vec::new(), } } } impl From<&IntrospectionNode> for Vec<IntrospectionReportItem> { fn from(node: &IntrospectionNode) -> Self { fn collect_report_items( node: &Introspect...
rust_dataset_chunk_921
rust_dataset.txt
921
512
= self.next_scope_id; self.next_scope_id += 1; scope_id } pub(crate) fn register_service( &mut self, info: RouteInfo, is_resource: bool, is_prefix: bool, scope_id: Option<usize>, parent_scope_id: Option<usize>, ) { let full_path = nor...
rust_dataset_chunk_922
rust_dataset.txt
922
512
&info.guard_details); update_unique(&mut d.patterns, &info.patterns); if d.resource_name.is_none() { d.resource_name = info.resource_name.clone(); } if !d.is_resource && is_resource { d.is_resource = true; ...
rust_dataset_chunk_923
rust_dataset.txt
923
512
() { current_node.resource_name = detail.resource_name.clone(); } } } } let reachability = analyze_reachability(&registrations); apply_reachability(&mut root, &reachability); IntrospectionTree { root, externals } ...
rust_dataset_chunk_924
rust_dataset.txt
924
512
in guard_details { merge_guard_detail_reports(&mut details, detail.into()); } } GuardReport { name: guard.name(), details, } }) .collect() } impl From<GuardDetail> for GuardDetailReport { fn fro...
rust_dataset_chunk_925
rust_dataset.txt
925
512
} } if reg.kind == RegistrationKind::Route { if let Some(context) = shadowed_routes.get(&(reg.scope_id, reg.full_path.clone())) { notes.push("shadowed_by_route".to_string()); notes.push(format!("shadowed_by_path:{}", context.path)); notes.pus...
rust_dataset_chunk_926
rust_dataset.txt
926
512
), Vec<&Registration>> = BTreeMap::new(); for reg in registrations { if reg.kind != RegistrationKind::Route { continue; } groups .entry((reg.scope_id, reg.full_path.clone())) .or_default() .push(reg); } let mut shadowed = BTreeMap::n...
rust_dataset_chunk_927
rust_dataset.txt
927
512
fn split_path_segments(path: &str) -> Vec<&str> { let trimmed = path.strip_prefix('/').unwrap_or(path); if trimmed.is_empty() { return vec![""]; } trimmed.split('/').collect() } fn matches_all(methods: &[Method], guards: &[String]) -> bool { methods.is_empty() && filter_guard_names(guards...
rust_dataset_chunk_928
rust_dataset.txt
928
512
Some(a) } } } fn intersect_methods( left: Option<BTreeSet<String>>, right: Option<BTreeSet<String>>, ) -> Option<BTreeSet<String>> { match (left, right) { (None, x) | (x, None) => x, (Some(a), Some(b)) => Some(a.intersection(&b).cloned()....
rust_dataset_chunk_929
rust_dataset.txt
929
512
Vec<GuardReport>, incoming: &[GuardReport]) { for report in incoming { if let Some(existing_report) = existing.iter_mut().find(|r| r.name == report.name) { for detail in &report.details { merge_guard_detail_reports(&mut existing_report.details, detail.clone()); } ...
rust_dataset_chunk_930
rust_dataset.txt
930
512
&str) -> String { // Escape control characters to keep the text report format stable in logs/terminals. let mut buf = String::with_capacity(value.len()); for ch in value.chars() { if ch.is_control() { let code = ch as u32; if code <= 0xFF { write!(buf, "\\x{:...
rust_dataset_chunk_931
rust_dataset.txt
931
512
= vec![GuardReport { name: "Header(accept, text/plain)".to_string(), details: vec![GuardDetailReport::Headers { headers: vec![HeaderReport { name: "accept".to_string(), value: "text/plain".to_string(), }], }], ...
rust_dataset_chunk_932
rust_dataset.txt
932
512
let items: Vec<IntrospectionReportItem> = (&tree.root).into(); let item = items .iter() .find(|item| item.full_path == "/all-guard") .expect("Missing route"); assert!(item.potentially_unreachable); assert!(item .reachability_notes .c...
rust_dataset_chunk_933
rust_dataset.txt
933
512
let scope_a = collector.next_scope_id(); let info = route_info( "/extra", Vec::new(), Vec::new(), Vec::new(), Vec::new(), None, ); collector.register_service(info, true, true, Some(scope_a), None); let info =...
rust_dataset_chunk_934
rust_dataset.txt
934
512
Item> = (&tree.root).into(); let item = items .iter() .find(|item| item.full_path == "/shadow") .expect("Missing route"); assert!(item.potentially_unreachable); assert!(item .reachability_notes .contains(&"shadowed_by_route".to_string...
rust_dataset_chunk_935
rust_dataset.txt
935
512
inspecting, //! and otherwise utilizing them. //! //! # Features //! - Supports HTTP/1.x and HTTP/2 //! - Streaming and pipelining //! - Powerful [request routing](https://actix.rs/docs/url-dispatch/) with optional macros //! - Full [Tokio](https://tokio.rs) compatibility //! - Keep-alive and slow requests handling ...
rust_dataset_chunk_936
rust_dataset.txt
936
512
_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_cfg))] #[cfg(all(test, feature = "macros"))] extern crate self as actix_web; pub use actix_http::{body, HttpMessage}; #[cfg(feature = "cookies")] #[doc(inline)] pub use cookie; pub ...
rust_dataset_chunk_937
rust_dataset.txt
937
512
MessageBody}, dev::{Service, Transform}, error::Error, service::ServiceResponse, }; /// Middleware for enabling any middleware to be used in [`Resource::wrap`](crate::Resource::wrap), /// and [`Condition`](super::Condition). /// /// # Examples /// ``` /// use actix_web::middleware::{Logger, Compat}; /// u...
rust_dataset_chunk_938
rust_dataset.txt
938
512
.service.call(req); CompatMiddlewareFuture { fut } } } pin_project! { pub struct CompatMiddlewareFuture<Fut> { #[pin] fut: Fut, } } impl<Fut, T, E> Future for CompatMiddlewareFuture<Fut> where Fut: Future<Output = Result<T, E>>, T: MapServiceResponseBody, E: Into<Error>...
rust_dataset_chunk_939
rust_dataset.txt
939
512
assert_eq!(resp.status(), StatusCode::OK); } #[tokio::test(flavor = "local")] #[cfg(all(feature = "cookies", feature = "__compress"))] async fn test_resource_scope_middleware() { use crate::middleware::Compress; let logger = Logger::default(); let compress = Compress::d...
rust_dataset_chunk_940
rust_dataset.txt
940
512
::ready; use mime::Mime; use once_cell::sync::Lazy; use pin_project_lite::pin_project; use crate::{ body::{EitherBody, MessageBody}, http::{ header::{self, AcceptEncoding, ContentEncoding, Encoding, HeaderValue}, StatusCode, }, service::{ServiceRequest, ServiceResponse}, Error, Http...
rust_dataset_chunk_941
rust_dataset.txt
941
512
(header::ContentEncoding::Gzip)) /// } /// /// let app = App::new() /// .wrap(middleware::Compress::default()) /// .default_service(web::to(index_handler)); /// ``` /// /// [feature flags]: ../index.html#crate-features #[derive(Debug, Clone, Default)] #[non_exhaustive] pub struct Compress; #[expect(deprecated,...
rust_dataset_chunk_942
rust_dataset.txt
942
512
ED_ENCODINGS_STRING.as_str(), ); res.headers_mut() .insert(header::VARY, HeaderValue::from_static("Accept-Encoding")); Either::right(ready(Ok(req .into_response(res) .map_into_boxed_body() ....
rust_dataset_chunk_943
rust_dataset.txt
943
512
} } static SUPPORTED_ENCODINGS_STRING: Lazy<String> = Lazy::new(|| { #[allow(unused_mut)] // only unused when no compress features enabled let mut encoding: Vec<&str> = vec![]; #[cfg(feature = "compress-brotli")] { encoding.push("br"); } #[cfg(feature = "compress-gzip")] { ...
rust_dataset_chunk_944
rust_dataset.txt
944
512
>, ct: &str) { assert!(res.status().is_success()); assert!( res.headers() .get(header::CONTENT_TYPE) .expect("Content-type header should be present") .to_str() .expect("Content-type header should be utf-8") .cont...
rust_dataset_chunk_945
rust_dataset.txt
945
512
(); let res = test::call_service(&app, req).await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.headers().get("x-double").unwrap(), "true"); assert_eq!(res.headers().get(header::CONTENT_ENCODING).unwrap(), "gzip"); let bytes = test::read_body(res).await; asser...
rust_dataset_chunk_946
rust_dataset.txt
946
512
"); assert_ne!(test::read_body(res).await, HTML_DATA.as_bytes()); let req = test::TestRequest::with_uri("/image").insert_header((header::ACCEPT_ENCODING, "gzip")); let res = test::call_service(&app, req.to_request()).await; assert_successful_identity_res_with_content_type(&r...
rust_dataset_chunk_947
rust_dataset.txt
947
512
.wrap(Compress::default()) .default_service(web::to(move || HttpResponse::Ok().finish())) }) .await; let req = test::TestRequest::default() .insert_header((header::ACCEPT_ENCODING, "br")) .to_request(); let res = test::call_service(&app, req).awa...
rust_dataset_chunk_948
rust_dataset.txt
948
512
Self::Future { if self.enable { let fut = self.transformer.new_transform(service); async move { let wrapped_svc = fut.await?; Ok(ConditionMiddleware::Enable(wrapped_svc)) } .boxed_local() } else { async move { O...
rust_dataset_chunk_949
rust_dataset.txt
949
512
fut.poll(cx))?.map_into_right_body(), }; Poll::Ready(Ok(res)) } } #[cfg(test)] mod tests { use actix_service::IntoService as _; use super::*; use crate::{ body::BoxBody, dev::ServiceRequest, error::Result, http::{ header::{HeaderValue, CONTE...
rust_dataset_chunk_950
rust_dataset.txt
950
512
Request| async move { let resp = HttpResponse::InternalServerError().message_body(String::new())?; Ok(req.into_response(resp)) }; let mw = ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, render_500); let mw = Condition::new(false, mw) .new_tr...
rust_dataset_chunk_951
rust_dataset.txt
951
512
# Panics /// Panics when resolved header name or value is invalid. #[allow(clippy::should_implement_trait)] pub fn add(mut self, header: impl TryIntoHeaderPair) -> Self { // standard header terminology `insert` or `append` for this method would make the behavior // of this middleware less o...
rust_dataset_chunk_952
rust_dataset.txt
952
512
InitError>>; fn new_transform(&self, service: S) -> Self::Future { ready(Ok(DefaultHeadersMiddleware { service, inner: Rc::clone(&self.inner), })) } } pub struct DefaultHeadersMiddleware<S> { service: S, inner: Rc<Inner>, } impl<S, B> Service<ServiceRequest> fo...
rust_dataset_chunk_953
rust_dataset.txt
953
512
HeaderValue::from_static("123"))) .new_transform(test::ok_service()) .await .unwrap(); let req = TestRequest::default().to_srv_request(); let res = mw.call(req).await.unwrap(); assert_eq!(res.headers().get("x-test").unwrap(), "0001"); assert_eq!(res....
rust_dataset_chunk_954
rust_dataset.txt
954
512
http::StatusCode, Error, Result, }; /// Return type for [`ErrorHandlers`] custom handlers. pub enum ErrorHandlerResponse<B> { /// Immediate HTTP response. Response(ServiceResponse<EitherBody<B>>), /// A future that resolves to an HTTP response. Future(LocalBoxFuture<'static, Result<ServiceRespons...
rust_dataset_chunk_955
rust_dataset.txt
955
512
response body: /// /// ``` /// use actix_web::{ /// dev::ServiceResponse, /// http::{header, StatusCode}, /// middleware::{ErrorHandlerResponse, ErrorHandlers}, /// web, App, HttpResponse, Result, /// }; /// /// fn add_error_body<B>(res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { /// ...
rust_dataset_chunk_956
rust_dataset.txt
956
512
App::new() /// .wrap( /// ErrorHandlers::new() /// .default_handler(add_error_header) /// .handler(StatusCode::BAD_REQUEST, handle_bad_request) /// ) /// .service(web::resource("/").route(web::get().to(HttpResponse::InternalServerError))); /// ``` /// /// You can set default...
rust_dataset_chunk_957
rust_dataset.txt
957
512
/// Construct new `ErrorHandlers` instance. pub fn new() -> Self { ErrorHandlers::default() } /// Register error handler for specified status code. pub fn handler<F>(mut self, status: StatusCode, handler: F) -> Self where F: Fn(ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>>...
rust_dataset_chunk_958
rust_dataset.txt
958
512
status code. /// /// If the `handlers` map has an entry for that status code, that handler is returned. /// Otherwise, fall back on the appropriate default handler. fn get_handler<'a>( status: &StatusCode, default_client: Option<&'a ErrorHandler<B>>, default_server: Option<&'a E...
rust_dataset_chunk_959
rust_dataset.txt
959
512
self.default_server.clone(); let fut = self.service.call(req); ErrorHandlersFuture::ServiceFuture { fut, default_client, default_server, handlers, } } } pin_project! { #[project = ErrorHandlersProj] pub enum ErrorHandlersFuture<Fut, B...
rust_dataset_chunk_960
rust_dataset.txt
960
512
_handler() { #[allow(clippy::unnecessary_wraps)] fn error_handler<B>(mut res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> { res.response_mut() .headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0001")); Ok(ErrorHandlerRespon...
rust_dataset_chunk_961
rust_dataset.txt
961
512
); let mw = ErrorHandlers::new() .handler(StatusCode::INTERNAL_SERVER_ERROR, error_handler) .new_transform(srv.into_service()) .await .unwrap(); let res = test::call_service(&mw, TestRequest::default().to_srv_request()).await; assert_eq!(test::re...
rust_dataset_chunk_962
rust_dataset.txt
962
512
default().to_srv_request()).await; assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001"); } #[tokio::test(flavor = "local")] async fn default_handlers_separate_client_server() { #[allow(clippy::unnecessary_wraps)] fn error_handler_client<B>(mut res: ServiceResponse<B>) -> Re...
rust_dataset_chunk_963
rust_dataset.txt
963
512
.headers_mut() .insert(CONTENT_TYPE, HeaderValue::from_static("0003")); Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) } let make_mw = |status| async move { ErrorHandlers::new() .default_handler_client(error_handler_client) ...
rust_dataset_chunk_964
rust_dataset.txt
964
512
/// ``` /// use actix_web::{ /// App, Error, /// dev::{ServiceRequest, ServiceResponse, Service as _}, /// }; /// use actix_web::middleware::from_fn; /// # use actix_web::middleware::Next; /// # async fn my_mw<B>(req: ServiceRequest, next: Next<B>) -> Result<ServiceResponse<B>, Error> { /// # next.call(req)...
rust_dataset_chunk_965
rust_dataset.txt
965
512
ServiceResponse<B>, Error = Error> + 'static, F: Fn(ServiceRequest, Next<B>) -> Fut + 'static, Fut: Future<Output = Result<ServiceResponse<B2>, Error>>, B2: MessageBody, { type Response = ServiceResponse<B2>; type Error = Error; type Transform = MiddlewareFnService<F, B, ()>; type InitError...
rust_dataset_chunk_966
rust_dataset.txt
966
512
static, B: MessageBody + 'static, B2: MessageBody + 'static, { type Response = ServiceResponse<B2>; type Error = Error; type Transform = MiddlewareFnService<F, B, ($($ext_type,)*)>; type InitError = (); type Future = Ready<Resul...
rust_dataset_chunk_967
rust_dataset.txt
967
512
, E3, E4, E5, E6, E7); impl_middleware_fn_service!(E1, E2, E3, E4, E5, E6, E7, E8); impl_middleware_fn_service!(E1, E2, E3, E4, E5, E6, E7, E8, E9); /// Wraps the "next" service in the middleware chain. #[allow(missing_debug_implementations)] pub struct Next<B> { service: RcService<ServiceRequest, ServiceResponse<...
rust_dataset_chunk_968
rust_dataset.txt
968
512
res = match self.0 { true => req.into_response("short-circuited").map_into_right_body(), false => next.call(req).await?.map_into_left_body(), }; res.headers_mut() .insert(header::WARNING, HeaderValue::from_static("42")); Ok(res) ...
rust_dataset_chunk_969
rust_dataset.txt
969
512
-web/actix-web/src/middleware/identity.rs --- //! A no-op middleware. See [Noop] for docs. #[expect(deprecated, reason = "preserve the public ready future type")] use actix_utils::future::{ready, Ready}; use crate::dev::{forward_ready, Service, Transform}; /// A no-op middleware that passes through request and respo...
rust_dataset_chunk_970
rust_dataset.txt
970
512
ServiceRequest, ServiceResponse}, Error, Result, }; /// Middleware for logging request and response summaries to the terminal. /// /// This middleware uses the `log` crate to output information. Enable `log`'s output for the /// "actix_web" scope using [`env_logger`](https://docs.rs/env_logger) or similar crate. /...
rust_dataset_chunk_971
rust_dataset.txt
971
512
{FOO}xo` | [Custom response replacement](Logger::custom_response_replace) labelled "FOO" /// /// # Security /// **\*** "Real IP" remote address is calculated using /// [`ConnectionInfo::realip_remote_addr()`](crate::dev::ConnectionInfo::realip_remote_addr()) /// /// If you use this value, ensure that all requests come ...
rust_dataset_chunk_972
rust_dataset.txt
972
512
1.0" 0.001985 /// + [2015-10-21T07:28:00Z INFO http_log] 127.0.0.1 "GET / HTTP/1.1" 200 88 "-" "dmc/1.0" 0.001985 /// ^^^^^^^^ /// ``` pub fn log_target(mut self, target: impl Into<Cow<'static, str>>) -> Self { let inner = Rc::get_mut(&mut self.0).unwrap(); ...
rust_dataset_chunk_973
rust_dataset.txt
973
512
/// .custom_request_replace("JWT_ID", |req| parse_jwt_id(req.headers().get("Authorization"))); /// ``` pub fn custom_request_replace( mut self, label: &str, f: impl Fn(&ServiceRequest) -> String + 'static, ) -> Self { let inner = Rc::get_mut(&mut self.0).unwrap(); ...
rust_dataset_chunk_974
rust_dataset.txt
974
512
if label == unit_label), ); if let Some(FormatText::CustomResponse(_, res_fn)) = ft { *res_fn = Some(CustomResponseFn { inner_fn: Rc::new(f), }); } else { debug!( "Attempted to register custom response logging function for non...
rust_dataset_chunk_975
rust_dataset.txt
975
512
>>; type Error = Error; type Future = LoggerResponse<S, B>; actix_service::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { let excluded = self.inner.exclude.contains(req.path()) || self .inner .exclude_regex ...
rust_dataset_chunk_976
rust_dataset.txt
976
512
since it's not usable in custom response functions anyway let (req, res) = res.into_parts(); let (res, body) = res.into_parts(); let temp_res = ServiceResponse::new(req, res.map_into_boxed_body()); for unit in &mut format.0 { unit.render_response(&temp...
rust_dataset_chunk_977
rust_dataset.txt
977
512
::Ready(None), } } } /// A formatting style for the `Logger` consisting of multiple concatenated `FormatText` items. #[derive(Debug, Clone)] struct Format(Vec<FormatText>); impl Default for Format { /// Return the default formatting style for the `Logger`: fn default() -> Format { Format::...
rust_dataset_chunk_978
rust_dataset.txt
978
512
"r" => FormatText::RequestLine, "s" => FormatText::ResponseStatus, "b" => FormatText::ResponseSize, "U" => FormatText::UrlPath, "T" => FormatText::Time, "D" => FormatText::TimeMillis, _ => FormatText...
rust_dataset_chunk_979
rust_dataset.txt
979
512
Percent => "%".fmt(fmt), FormatText::ResponseSize => size.fmt(fmt), FormatText::Time => { let rt = OffsetDateTime::now_utc() - entry_time; let rt = rt.as_seconds_f64(); fmt.write_fmt(format_args!("{:.6}", rt)) } FormatText::...
rust_dataset_chunk_980
rust_dataset.txt
980
512
(&Rfc3339).unwrap()), FormatText::RequestHeader(ref name) => { let s = if let Some(val) = req.headers().get(name) { String::from_utf8_lossy(val.as_bytes()).into_owned() } else { "-".to_owned() }; *self = ...
rust_dataset_chunk_981
rust_dataset.txt
981
512
await.unwrap(); let req = TestRequest::default() .insert_header(( header::USER_AGENT, header::HeaderValue::from_static("ACTIX-WEB"), )) .to_srv_request(); let _res = srv.call(req).await; } #[tokio::test(flavor = "local")] ...
rust_dataset_chunk_982
rust_dataset.txt
982
512
new("%T %U"); let req = TestRequest::default() .insert_header(( header::USER_AGENT, header::HeaderValue::from_static("ACTIX-WEB"), )) .uri("/test/route/yeah") .to_srv_request(); let now = OffsetDateTime::now_utc(); ...
rust_dataset_chunk_983
rust_dataset.txt
983
512
test_request_time_format() { let mut format = Format::new("%t"); let req = TestRequest::default().to_srv_request(); let now = OffsetDateTime::now_utc(); for unit in &mut format.0 { unit.render_request(now, &req); } let req = TestRequest::default().to_http_r...
rust_dataset_chunk_984
rust_dataset.txt
984
512
_mut(&mut logger.0).unwrap().format.0[1].clone(); let label = match &unit { FormatText::CustomRequest(label, _) => label, ft => panic!("Expected CustomRequest, found {:?}", ft), }; assert_eq!(label, "CUSTOM"); let req = TestRequest::default().to_srv_request(); ...
rust_dataset_chunk_985
rust_dataset.txt
985
512
} } --- FILE: actix-web/actix-web/src/middleware/mod.rs --- //! A collection of common middleware. //! //! # What Is Middleware? //! //! Actix Web's middleware system allows us to add additional behavior to request/response //! processing. Middleware can hook into incoming request and outgoing response processes,...
rust_dataset_chunk_986
rust_dataset.txt
986
512
types. //! //! # Ordering //! //! ``` //! # use actix_web::{web, middleware, get, App, Responder}; //! # //! # // some basic types to make sure this compiles //! # type ExtractorA = web::Json<String>; //! # type ExtractorB = ExtractorA; //! #[get("/")] //! async fn service(a: ExtractorA, b: ExtractorB) -> impl Respond...
rust_dataset_chunk_987
rust_dataset.txt
987
512
//! ``` //! The request _first_ gets processed by the middleware specified _last_ - `MiddlewareC`. It passes //! the request (possibly a modified one) to the next middleware - `MiddlewareB` - _or_ directly //! responds to the request (e.g. when the request was invalid or an error occurred). `MiddlewareB` //! processes ...
rust_dataset_chunk_988
rust_dataset.txt
988
512
a //! response of type [`S::Response`](crate::dev::Service::Response) or an error of type //! [`S::Error`](crate::dev::Service::Error). You can think of the service of being roughly: //! //! ```ignore //! async fn(&self, req: Req) -> Result<S::Response, S::Error> //! ``` //! //! In most cases the [`Service`] implement...
rust_dataset_chunk_989
rust_dataset.txt
989
512
//! S::Future: 'static, //! B: 'static, //! { //! type Response = ServiceResponse<B>; //! type Error = Error; //! type Future = LocalBoxFuture<Result<Self::Response, Self::Error>>; //! //! // This service is ready when its next service is ready //! forward_ready!(service); //! //! fn cal...
rust_dataset_chunk_990
rust_dataset.txt
990
512
new().add(("X-Test2", "X-Value2"))) .wrap(ErrorHandlers::new().handler(StatusCode::FORBIDDEN, |res| { Ok(ErrorHandlerResponse::Response(res.map_into_left_body())) })) .wrap(Logger::default()) .wrap(NormalizePath::new(TrailingSlash::Trim)); let _ =...
rust_dataset_chunk_991
rust_dataset.txt
991
512
if new_idx < new_path.len() && old_path[old_idx] == new_path[new_idx] { new_idx += 1; } old_idx += 1; map.push(new_idx.min(u16::MAX as usize) as u16); } map } /// Determines the behavior of the [`NormalizePath`] middleware. /// /// The default is `TrailingSlash::Trim`. #[...
rust_dataset_chunk_992
rust_dataset.txt
992
512
/// use actix_web::test::{call_service, init_service, TestRequest}; /// /// let app = init_service(app).await; /// /// let req = TestRequest::with_uri("/test").to_request(); /// let res = call_service(&app, req).await; /// assert_eq!(res.status(), StatusCode::OK); /// /// let req = TestRequest::with_uri("/test/").to_re...
rust_dataset_chunk_993
rust_dataset.txt
993
512
service: S) -> Self::Future { ready(Ok(NormalizePathNormalization { service, merge_slash: Regex::new("//+").unwrap(), trailing_slash_behavior: self.0, })) } } pub struct NormalizePathNormalization<S> { service: S, merge_slash: Regex, trailing_slash_b...
rust_dataset_chunk_994
rust_dataset.txt
994
512
!= original_path { let reindex = build_byte_index_map(original_path, path); let mut parts = head.uri.clone().into_parts(); let query = parts.path_and_query.as_ref().and_then(|pq| pq.query()); let path = match query { Some(q) => Bytes:...
rust_dataset_chunk_995
rust_dataset.txt
995
512
assert!(res.status().is_success(), "Failed uri: {}", uri); } } #[tokio::test(flavor = "local")] async fn trim_trailing_slashes() { let app = init_service( App::new() .wrap(NormalizePath(TrailingSlash::Trim)) .service(web::resource("/").to(HttpRes...
rust_dataset_chunk_996
rust_dataset.txt
996
512
::new() .wrap(NormalizePath(TrailingSlash::Always)) .service(web::resource("/").to(HttpResponse::Ok)) .service(web::resource("/v1/something/").to(HttpResponse::Ok)) .service( web::resource("/v2/something/") .guar...
rust_dataset_chunk_997
rust_dataset.txt
997
512
omething").to(HttpResponse::Ok)) .service(web::resource("/v1/").to(HttpResponse::Ok)) .service( web::resource("/v2/something") .guard(fn_guard(|ctx| ctx.head().uri.query() == Some("query=test"))) .to(HttpResponse::Ok), ...
rust_dataset_chunk_998
rust_dataset.txt
998
512
service(web::resource("/v1").to(HttpResponse::Ok)), ), ) .await; let req = TestRequest::with_uri("/api//v1").to_request(); let res = call_service(&app, req).await; assert_eq!(res.status(), StatusCode::OK); } #[tokio::test(flavor = "local")] async fn no_...
rust_dataset_chunk_999
rust_dataset.txt
999
512
res = normalize.call(req).await.unwrap(); assert!(res.status().is_success()); } #[tokio::test(flavor = "local")] async fn should_normalize_no_trail() { let srv = |req: ServiceRequest| { assert_eq!("/v1/something", req.path()); ready(Ok(req.into_response(HttpResponse...