code
stringlengths
40
729k
docstring
stringlengths
22
46.3k
func_name
stringlengths
1
97
language
stringclasses
1 value
repo
stringlengths
6
48
path
stringlengths
8
176
url
stringlengths
47
228
license
stringclasses
7 values
fn default() -> Self { Catcher { goal: Arc::new(DefaultGoal::new()), hoops: vec![], } }
Create new `Catcher` with its goal handler is [`DefaultGoal`].
default
rust
salvo-rs/salvo
crates/core/src/catcher.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/catcher.rs
Apache-2.0
pub async fn catch(&self, req: &mut Request, depot: &mut Depot, res: &mut Response) { let mut ctrl = FlowCtrl::new(self.hoops.iter().chain([&self.goal]).cloned().collect()); ctrl.call_next(req, depot, res).await; }
Catch error and send error page.
catch
rust
salvo-rs/salvo
crates/core/src/catcher.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/catcher.rs
Apache-2.0
pub fn footer(mut self, footer: impl Into<Cow<'static, str>>) -> Self { self.footer = Some(footer.into()); self }
Set custom footer which is only used in html error page. If footer is `None`, then use default footer. Default footer is `<a href="https://salvo.rs" target="_blank">salvo</a>`.
footer
rust
salvo-rs/salvo
crates/core/src/catcher.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/catcher.rs
Apache-2.0
pub fn get_mut<V: Any + Send + Sync>( &mut self, key: &str, ) -> Result<&mut V, Option<&mut Box<dyn Any + Send + Sync>>> { if let Some(value) = self.map.get_mut(key) { if value.downcast_mut::<V>().is_some() { Ok(value .downcast_mut::<V>() .expect("downcast_mut should not be failed")) } else { Err(Some(value)) } } else { Err(None) } }
Mutably borrows value from depot. Returns `Err(None)` if value is not present in depot. Returns `Err(Some(Box<dyn Any + Send + Sync>))` if value is present in depot but downcasting failed.
get_mut
rust
salvo-rs/salvo
crates/core/src/depot.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/depot.rs
Apache-2.0
pub fn stop_forcible(&self) { let _ = self.tx_cmd.send(ServerCommand::StopForcible); }
Force stop server. Call this function will stop server immediately.
stop_forcible
rust
salvo-rs/salvo
crates/core/src/server.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/server.rs
Apache-2.0
pub fn stop_graceful(&self, timeout: impl Into<Option<Duration>>) { let _ = self.tx_cmd.send(ServerCommand::StopGraceful(timeout.into())); }
Graceful stop server. Call this function will stop server after all connections are closed, allowing it to finish processing any ongoing requests before terminating. It ensures that all connections are closed properly and any resources are released. You can specify a timeout to force stop server. If `timeout` is `None`, it will wait until all connections are closed. This function gracefully stop the server, allowing it to finish processing any ongoing requests before terminating. It ensures that all connections are closed properly and any resources are released. # Examples ```no_run use salvo_core::prelude::*; #[tokio::main] async fn main() { let acceptor = TcpListener::new("127.0.0.1:5800").bind().await; let server = Server::new(acceptor); let handle = server.handle(); // Graceful shutdown the server tokio::spawn(async move { tokio::time::sleep(std::time::Duration::from_secs(60)).await; handle.stop_graceful(None); }); server.serve(Router::new()).await; } ```
stop_graceful
rust
salvo-rs/salvo
crates/core/src/server.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/server.rs
Apache-2.0
pub fn new(acceptor: A) -> Self { Self::with_http_builder(acceptor, HttpBuilder::new()) }
Create new `Server` with [`Acceptor`]. # Example ```no_run use salvo_core::prelude::*; #[tokio::main] async fn main() { let acceptor = TcpListener::new("127.0.0.1:5800").bind().await; Server::new(acceptor); } ```
new
rust
salvo-rs/salvo
crates/core/src/server.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/server.rs
Apache-2.0
pub fn with_http_builder(acceptor: A, builder: HttpBuilder) -> Self { #[cfg(feature = "server-handle")] let (tx_cmd, rx_cmd) = tokio::sync::mpsc::unbounded_channel(); Self { acceptor, builder, fuse_factory: None, #[cfg(feature = "server-handle")] tx_cmd, #[cfg(feature = "server-handle")] rx_cmd, } }
Create new `Server` with [`Acceptor`] and [`HttpBuilder`].
with_http_builder
rust
salvo-rs/salvo
crates/core/src/server.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/server.rs
Apache-2.0
pub fn ttl(mut self, ttl: u32) -> Self { self.ttl = Some(ttl); self }
Sets the value for the `IP_TTL` option on this socket. This value sets the time-to-live field that is used in every packet sent from this socket.
ttl
rust
salvo-rs/salvo
crates/core/src/conn/tcp.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/tcp.rs
Apache-2.0
pub fn owner(mut self, uid: Option<u32>, gid: Option<u32>) -> Self { self.owner = Some((uid.map(Uid::from_raw), gid.map(Gid::from_raw))); self }
Provides owner to be set on actual bind.
owner
rust
salvo-rs/salvo
crates/core/src/conn/unix.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/unix.rs
Apache-2.0
pub fn build(self) -> IoResult<AcmeConfig> { self.directory_url .parse::<Uri>() .map_err(|e| IoError::other(format!("invalid directory url: {}", e)))?; if self.domains.is_empty() { return Err(IoError::other("at least one domain name is expected")); } let Self { directory_name, directory_url, domains, contacts, challenge_type, cache_path, keys_for_http01, before_expired, } = self; Ok(AcmeConfig { directory_name, directory_url, domains, contacts, key_pair: Arc::new(KeyPair::generate()?), challenge_type, cache_path, keys_for_http01, before_expired, }) }
Consumes this builder and returns a [`AcmeConfig`] object.
build
rust
salvo-rs/salvo
crates/core/src/conn/acme/config.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/acme/config.rs
Apache-2.0
pub fn http01_challenge(self, router: &mut Router) -> Self { let config_builder = self.config_builder.http01_challenge(); if let Some(keys_for_http01) = &config_builder.keys_for_http01 { let handler = Http01Handler { keys: keys_for_http01.clone(), }; router.routers.insert( 0, Router::with_path(format!("{}/{{token}}", WELL_KNOWN_PATH)).goal(handler), ); } else { panic!("`HTTP-01` challenge's key should not be none"); } Self { config_builder, ..self } }
Create an handler for HTTP-01 challenge
http01_challenge
rust
salvo-rs/salvo
crates/core/src/conn/acme/listener.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/acme/listener.rs
Apache-2.0
pub async fn new<C, O>(conn: C) -> Result<(Connection<C, Bytes>, SendRequest<O, Bytes>), Error> where C: quic::Connection<Bytes, OpenStreams = O>, O: quic::OpenStreams<Bytes>, { //= https://www.rfc-editor.org/rfc/rfc9114#section-3.3 //= type=implication //# Clients SHOULD NOT open more than one HTTP/3 connection to a given IP //# address and UDP port, where the IP address and port might be derived //# from a URI, a selected alternative service ([ALTSVC]), a configured //# proxy, or name resolution of any of these. Builder::new().build(conn).await }
Create a new HTTP/3 client with default settings
new
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub async fn send_request(&mut self, req: http::Request<()>) -> Result<RequestStream<T::BidiStream, B>, Error> { let (peer_max_field_section_size, closing) = { let state = self.conn_state.read("send request lock state"); (state.peer_max_field_section_size, state.closing) }; if closing.is_some() { return Err(Error::closing()); } let (parts, _) = req.into_parts(); let request::Parts { method, uri, headers, .. } = parts; let headers = Header::request(method, uri, headers)?; //= https://www.rfc-editor.org/rfc/rfc9114#section-4.1 //= type=implication //# A //# client MUST send only a single request on a given stream. let mut stream = future::poll_fn(|cx| self.open.poll_open_bidi(cx)) .await .map_err(|e| self.maybe_conn_err(e))?; //= https://www.rfc-editor.org/rfc/rfc9114#section-4.2 //= type=TODO //# Characters in field names MUST be //# converted to lowercase prior to their encoding. //= https://www.rfc-editor.org/rfc/rfc9114#section-4.2.1 //= type=TODO //# To allow for better compression efficiency, the Cookie header field //# ([COOKIES]) MAY be split into separate field lines, each with one or //# more cookie-pairs, before compression. let mut block = BytesMut::new(); let mem_size = qpack::encode_stateless(&mut block, headers)?; //= https://www.rfc-editor.org/rfc/rfc9114#section-4.2.2 //# An implementation that //# has received this parameter SHOULD NOT send an HTTP message header //# that exceeds the indicated size, as the peer will likely refuse to //# process it. if mem_size > peer_max_field_section_size { return Err(Error::header_too_big(mem_size, peer_max_field_section_size)); } stream::write(&mut stream, Frame::Headers(block.freeze())) .await .map_err(|e| self.maybe_conn_err(e))?; let request_stream = RequestStream { inner: connection::RequestStream::new( FrameStream::new(stream), self.max_field_section_size, self.conn_state.clone(), self.send_grease_frame, ), }; // send the grease frame only once self.send_grease_frame = false; Ok(request_stream) }
Send a HTTP/3 request to the server
send_request
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub async fn wait_idle(&mut self) -> Result<(), Error> { future::poll_fn(|cx| self.poll_close(cx)).await }
Wait until the connection is closed
wait_idle
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub fn poll_close(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Error>> { while let Poll::Ready(result) = self.inner.poll_control(cx) { match result { //= https://www.rfc-editor.org/rfc/rfc9114#section-7.2.4.2 //= type=TODO //# When a 0-RTT QUIC connection is being used, the initial value of each //# server setting is the value used in the previous session. Clients //# SHOULD store the settings the server provided in the HTTP/3 //# connection where resumption information was provided, but they MAY //# opt not to store settings in certain cases (e.g., if the session //# ticket is received before the SETTINGS frame). //= https://www.rfc-editor.org/rfc/rfc9114#section-7.2.4.2 //= type=TODO //# A client MUST comply //# with stored settings -- or default values if no values are stored -- //# when attempting 0-RTT. //= https://www.rfc-editor.org/rfc/rfc9114#section-7.2.4.2 //= type=TODO //# Once a server has provided new settings, //# clients MUST comply with those values. Ok(Frame::Settings(_)) => trace!("Got settings"), Ok(Frame::Goaway(id)) => { //= https://www.rfc-editor.org/rfc/rfc9114#section-7.2.6 //# The GOAWAY frame is always sent on the control stream. In the //# server-to-client direction, it carries a QUIC stream ID for a client- //# initiated bidirectional stream encoded as a variable-length integer. //# A client MUST treat receipt of a GOAWAY frame containing a stream ID //# of any other type as a connection error of type H3_ID_ERROR. if !id.is_request() { return Poll::Ready(Err(Code::H3_ID_ERROR.with_reason( format!("non-request StreamId in a GoAway frame: {}", id), ErrorLevel::ConnectionError, ))); } info!("Server initiated graceful shutdown, last: StreamId({})", id); } //= https://www.rfc-editor.org/rfc/rfc9114#section-7.2.5 //# If a PUSH_PROMISE frame is received on the control stream, the client //# MUST respond with a connection error of type H3_FRAME_UNEXPECTED. //= https://www.rfc-editor.org/rfc/rfc9114#section-7.2.7 //# A client MUST treat the //# receipt of a MAX_PUSH_ID frame as a connection error of type //# H3_FRAME_UNEXPECTED. Ok(frame) => { return Poll::Ready(Err(Code::H3_FRAME_UNEXPECTED.with_reason( format!("on client control stream: {:?}", frame), ErrorLevel::ConnectionError, ))) } Err(e) => { let connection_error = self.inner.shared.read("poll_close error read").error.as_ref().cloned(); match connection_error { Some(e) if e.is_closed() => return Poll::Ready(Ok(())), Some(e) => return Poll::Ready(Err(e)), None => { self.inner.shared.write("poll_close error").error = e.clone().into(); return Poll::Ready(Err(e)); } } } } } //= https://www.rfc-editor.org/rfc/rfc9114#section-6.1 //# Clients MUST treat //# receipt of a server-initiated bidirectional stream as a connection //# error of type H3_STREAM_CREATION_ERROR unless such an extension has //# been negotiated. if self.inner.poll_accept_request(cx).is_ready() { return Poll::Ready(Err(self .inner .close(Code::H3_STREAM_CREATION_ERROR, "client received a bidirectional stream"))); } Poll::Pending }
Maintain the connection state until it is closed
poll_close
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub fn max_field_section_size(&mut self, value: u64) -> &mut Self { self.max_field_section_size = value; self }
Set the maximum header size this client is willing to accept See [header size constraints] section of the specification for details. [header size constraints]: https://www.rfc-editor.org/rfc/rfc9114.html#name-header-size-constraints
max_field_section_size
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub async fn build<C, O, B>(&mut self, quic: C) -> Result<(Connection<C, B>, SendRequest<O, B>), Error> where C: quic::Connection<B, OpenStreams = O>, O: quic::OpenStreams<B>, B: Buf, { let open = quic.opener(); let conn_state = SharedStateRef::default(); let conn_waker = Some(future::poll_fn(|cx| Poll::Ready(cx.waker().clone())).await); Ok(( Connection { inner: ConnectionInner::new(quic, self.max_field_section_size, conn_state.clone(), self.send_grease) .await?, }, SendRequest { open, conn_state, conn_waker, max_field_section_size: self.max_field_section_size, sender_count: Arc::new(AtomicUsize::new(1)), _buf: PhantomData, send_grease_frame: self.send_grease, }, )) }
Create a new HTTP/3 client from a `quic` connection
build
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub async fn recv_response(&mut self) -> Result<Response<()>, Error> { let mut frame = future::poll_fn(|cx| self.inner.stream.poll_next(cx)) .await .map_err(|e| self.maybe_conn_err(e))? .ok_or_else(|| { Code::H3_GENERAL_PROTOCOL_ERROR .with_reason("Did not receive response headers", ErrorLevel::ConnectionError) })?; //= https://www.rfc-editor.org/rfc/rfc9114#section-7.2.5 //= type=TODO //# A client MUST treat //# receipt of a PUSH_PROMISE frame that contains a larger push ID than //# the client has advertised as a connection error of H3_ID_ERROR. //= https://www.rfc-editor.org/rfc/rfc9114#section-7.2.5 //= type=TODO //# If a client //# receives a push ID that has already been promised and detects a //# mismatch, it MUST respond with a connection error of type //# H3_GENERAL_PROTOCOL_ERROR. let decoded = if let Frame::Headers(ref mut encoded) = frame { match qpack::decode_stateless(encoded, self.inner.max_field_section_size) { //= https://www.rfc-editor.org/rfc/rfc9114#section-4.2.2 //# An HTTP/3 implementation MAY impose a limit on the maximum size of //# the message header it will accept on an individual HTTP message. Err(qpack::DecoderError::HeaderTooLong(cancel_size)) => { self.inner.stop_sending(Code::H3_REQUEST_CANCELLED); return Err(Error::header_too_big(cancel_size, self.inner.max_field_section_size)); } Ok(decoded) => decoded, Err(e) => return Err(e.into()), } } else { return Err(Code::H3_FRAME_UNEXPECTED .with_reason("First response frame is not headers", ErrorLevel::ConnectionError)); }; let qpack::Decoded { fields, .. } = decoded; let (status, headers) = Header::try_from(fields)?.as_response_parts()?; let mut resp = Response::new(()); *resp.status_mut() = status; *resp.headers_mut() = headers; *resp.version_mut() = http::Version::HTTP_3; Ok(resp) }
Receive the HTTP/3 response This should be called before trying to receive any data with [`recv_data()`]. [`recv_data()`]: #method.recv_data
recv_response
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub async fn recv_trailers(&mut self) -> Result<Option<HeaderMap>, Error> { let res = self.inner.recv_trailers().await; if let Err(ref e) = res { if e.is_header_too_big() { self.inner.stream.stop_sending(Code::H3_REQUEST_CANCELLED); } } res }
Receive an optional set of trailers for the response.
recv_trailers
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub fn stop_sending(&mut self, error_code: crate::error::Code) { // TODO take by value to prevent any further call as this request is cancelled // rename `cancel()` ? self.inner.stream.stop_sending(error_code) }
Tell the peer to stop sending into the underlying QUIC stream
stop_sending
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub fn split(self) -> (RequestStream<S::SendStream, B>, RequestStream<S::RecvStream, B>) { let (send, recv) = self.inner.split(); (RequestStream { inner: send }, RequestStream { inner: recv }) }
Split this stream into two halves that can be driven independently.
split
rust
salvo-rs/salvo
crates/core/src/conn/quinn/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/quinn/client.rs
Apache-2.0
pub fn client_auth_optional_path(mut self, path: impl AsRef<Path>) -> IoResult<Self> { let mut data = vec![]; let mut file = File::open(path)?; file.read_to_end(&mut data)?; self.client_auth = TlsClientAuth::Optional(data); Ok(self) }
Sets the trust anchor for optional Tls client authentication via file path. Anonymous and authenticated clients will be accepted. If no trust anchor is provided by any of the `client_auth_` methods, then client authentication is disabled by default.
client_auth_optional_path
rust
salvo-rs/salvo
crates/core/src/conn/rustls/config.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/rustls/config.rs
Apache-2.0
pub fn client_auth_optional(mut self, trust_anchor: impl Into<Vec<u8>>) -> Self { self.client_auth = TlsClientAuth::Optional(trust_anchor.into()); self }
Sets the trust anchor for optional Tls client authentication via bytes slice. Anonymous and authenticated clients will be accepted. If no trust anchor is provided by any of the `client_auth_` methods, then client authentication is disabled by default.
client_auth_optional
rust
salvo-rs/salvo
crates/core/src/conn/rustls/config.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/rustls/config.rs
Apache-2.0
pub fn client_auth_required_path(mut self, path: impl AsRef<Path>) -> IoResult<Self> { let mut data = vec![]; let mut file = File::open(path)?; file.read_to_end(&mut data)?; self.client_auth = TlsClientAuth::Required(data); Ok(self) }
Sets the trust anchor for required Tls client authentication via file path. Only authenticated clients will be accepted. If no trust anchor is provided by any of the `client_auth_` methods, then client authentication is disabled by default.
client_auth_required_path
rust
salvo-rs/salvo
crates/core/src/conn/rustls/config.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/conn/rustls/config.rs
Apache-2.0
pub fn apply_to_variant(&self, variant: impl AsRef<str>) -> String { let variant = variant.as_ref(); match self { PascalCase => variant.to_owned(), LowerCase => variant.to_ascii_lowercase(), UpperCase => variant.to_ascii_uppercase(), CamelCase => variant[..1].to_ascii_lowercase() + &variant[1..], SnakeCase => { let mut snake = String::new(); for (i, ch) in variant.char_indices() { if i > 0 && ch.is_uppercase() { snake.push('_'); } snake.push(ch.to_ascii_lowercase()); } snake } ScreamingSnakeCase => SnakeCase.apply_to_variant(variant).to_ascii_uppercase(), KebabCase => SnakeCase.apply_to_variant(variant).replace('_', "-"), ScreamingKebabCase => ScreamingSnakeCase .apply_to_variant(variant) .replace('_', "-"), } }
Apply a renaming rule to an enum variant, returning the version expected in the source.
apply_to_variant
rust
salvo-rs/salvo
crates/core/src/extract/case.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/case.rs
Apache-2.0
pub fn apply_to_field(self, field: &str) -> String { match self { LowerCase | SnakeCase => field.to_owned(), UpperCase => field.to_ascii_uppercase(), PascalCase => { let mut pascal = String::new(); let mut capitalize = true; for ch in field.chars() { if ch == '_' { capitalize = true; } else if capitalize { pascal.push(ch.to_ascii_uppercase()); capitalize = false; } else { pascal.push(ch); } } pascal } CamelCase => { let pascal = PascalCase.apply_to_field(field); pascal[..1].to_ascii_lowercase() + &pascal[1..] } ScreamingSnakeCase => field.to_ascii_uppercase(), KebabCase => field.replace('_', "-"), ScreamingKebabCase => ScreamingSnakeCase.apply_to_field(field).replace('_', "-"), } }
Apply a renaming rule to a struct field, returning the version expected in the source.
apply_to_field
rust
salvo-rs/salvo
crates/core/src/extract/case.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/case.rs
Apache-2.0
pub fn default_sources(mut self, default_sources: Vec<Source>) -> Self { self.default_sources = default_sources; self }
Sets the default sources list to a new value.
default_sources
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn fields(mut self, fields: Vec<Field>) -> Self { self.fields = fields; self }
set all fields list to a new value.
fields
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn add_default_source(mut self, source: Source) -> Self { self.default_sources.push(source); self }
Add a default source to default sources list.
add_default_source
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn add_field(mut self, field: Field) -> Self { self.fields.push(field); self }
Add a field to the fields list.
add_field
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn rename_all(mut self, rename_all: impl Into<Option<RenameRule>>) -> Self { self.rename_all = rename_all.into(); self }
Rule for rename all fields of type.
rename_all
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn serde_rename_all(mut self, serde_rename_all: impl Into<Option<RenameRule>>) -> Self { self.serde_rename_all = serde_rename_all.into(); self }
Rule for rename all fields of type defined by serde.
serde_rename_all
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub(crate) fn has_body_required(&self) -> bool { if self .default_sources .iter() .any(|s| s.from == SourceFrom::Body) { return true; } self.fields.iter().any(|f| f.has_body_required()) }
Check is this type has body required.
has_body_required
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn new(decl_name: &'static str) -> Self { Self::with_sources(decl_name, vec![]) }
Create a new field with the given name and kind.
new
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn with_sources(decl_name: &'static str, sources: Vec<Source>) -> Self { Self { decl_name, flatten: false, sources, aliases: vec![], rename: None, serde_rename: None, metadata: None, } }
Create a new field with the given name and kind, and the given sources.
with_sources
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn flatten(mut self, flatten: bool) -> Self { self.flatten = flatten; self }
Sets the flatten to the given value.
flatten
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn metadata(mut self, metadata: &'static Metadata) -> Self { self.metadata = Some(metadata); self }
Sets the metadata to the field type.
metadata
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn aliases(mut self, aliases: Vec<&'static str>) -> Self { self.aliases = aliases; self }
Sets the aliases list to a new value.
aliases
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn rename(mut self, rename: &'static str) -> Self { self.rename = Some(rename); self }
Sets the rename to the given value.
rename
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub fn serde_rename(mut self, serde_rename: &'static str) -> Self { self.serde_rename = Some(serde_rename); self }
Sets the rename to the given value.
serde_rename
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
pub(crate) fn has_body_required(&self) -> bool { self.sources.iter().any(|s| s.from == SourceFrom::Body) }
Check is this field has body required.
has_body_required
rust
salvo-rs/salvo
crates/core/src/extract/metadata.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/metadata.rs
Apache-2.0
fn extract_with_arg( req: &'ex mut Request, _arg: &str, ) -> impl Future<Output = Result<Self, impl Writer + Send + Debug + 'static>> + Send where Self: Sized, { Self::extract(req) }
Extract data from request with a argument. This function used in macros internal.
extract_with_arg
rust
salvo-rs/salvo
crates/core/src/extract/mod.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/extract/mod.rs
Apache-2.0
pub async fn send(self, req_headers: &HeaderMap, res: &mut Response) { if !self.path.exists() { res.render(StatusError::not_found()); } else { match self.build().await { Ok(file) => file.send(req_headers, res).await, Err(_) => res.render(StatusError::internal_server_error()), } } }
Build a new `NamedFile` and send it.
send
rust
salvo-rs/salvo
crates/core/src/fs/named_file.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/fs/named_file.rs
Apache-2.0
pub async fn send(mut self, req_headers: &HeaderMap, res: &mut Response) { let etag = if self.flags.contains(Flag::Etag) { self.etag() } else { None }; let last_modified = if self.flags.contains(Flag::LastModified) { self.last_modified() } else { None }; // check preconditions let precondition_failed = if !any_match(etag.as_ref(), req_headers) { true } else if let (Some(last_modified), Some(since)) = (&last_modified, req_headers.typed_get::<IfUnmodifiedSince>()) { !since.precondition_passes(*last_modified) } else { false }; // check last modified let not_modified = if !none_match(etag.as_ref(), req_headers) { true } else if req_headers.contains_key(IF_NONE_MATCH) { false } else if let (Some(last_modified), Some(since)) = (&last_modified, req_headers.typed_get::<IfModifiedSince>()) { !since.is_modified(*last_modified) } else { false }; if self.flags.contains(Flag::ContentDisposition) { if let Some(content_disposition) = self.content_disposition.take() { res.headers_mut() .insert(CONTENT_DISPOSITION, content_disposition); } else if !res.headers().contains_key(CONTENT_DISPOSITION) { // skip to set CONTENT_DISPOSITION header if it is already set. match build_content_disposition(&self.path, &self.content_type, None, None) { Ok(content_disposition) => { res.headers_mut() .insert(CONTENT_DISPOSITION, content_disposition); } Err(e) => { tracing::error!(error = ?e, "build file's content disposition failed"); } } } } if !res.headers().contains_key(CONTENT_TYPE) { res.headers_mut() .typed_insert(ContentType::from(self.content_type.clone())); } if let Some(lm) = last_modified { res.headers_mut().typed_insert(LastModified::from(lm)); } if let Some(etag) = self.etag() { res.headers_mut().typed_insert(etag); } res.headers_mut().typed_insert(AcceptRanges::bytes()); let mut length = self.metadata.len(); if let Some(content_encoding) = &self.content_encoding { res.headers_mut() .insert(CONTENT_ENCODING, content_encoding.clone()); } let mut offset = 0; // check for range header let range = req_headers.get(RANGE); if let Some(range) = range { if let Ok(range) = range.to_str() { if let Ok(range) = HttpRange::parse(range, length) { length = range[0].length; offset = range[0].start; } else { res.headers_mut() .typed_insert(ContentRange::unsatisfied_bytes(length)); res.status_code(StatusCode::RANGE_NOT_SATISFIABLE); return; }; } else { res.status_code(StatusCode::BAD_REQUEST); return; }; } if precondition_failed { res.status_code(StatusCode::PRECONDITION_FAILED); return; } else if not_modified { res.status_code(StatusCode::NOT_MODIFIED); return; } if offset != 0 || length != self.metadata.len() || range.is_some() { res.status_code(StatusCode::PARTIAL_CONTENT); match ContentRange::bytes(offset..offset + length, self.metadata.len()) { Ok(content_range) => { res.headers_mut().typed_insert(content_range); } Err(e) => { tracing::error!(error = ?e, "set file's content ranage failed"); } } let reader = ChunkedFile { offset, total_size: cmp::min(length, self.metadata.len()), read_size: 0, state: ChunkedState::File(Some(self.file.into_std().await)), buffer_size: self.buffer_size, }; res.headers_mut() .typed_insert(ContentLength(reader.total_size)); res.stream(reader); } else { res.status_code(StatusCode::OK); let reader = ChunkedFile { offset, state: ChunkedState::File(Some(self.file.into_std().await)), total_size: length, read_size: 0, buffer_size: self.buffer_size, }; res.headers_mut().typed_insert(ContentLength(length)); res.stream(reader); } }
Consume self and send content to [`Response`].
send
rust
salvo-rs/salvo
crates/core/src/fs/named_file.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/fs/named_file.rs
Apache-2.0
fn any_match(etag: Option<&ETag>, req_headers: &HeaderMap) -> bool { match req_headers.typed_get::<IfMatch>() { None => true, Some(if_match) => { if if_match == IfMatch::any() { true } else if let Some(etag) = etag { if_match.precondition_passes(etag) } else { false } } } }
Returns true if `req_headers` has no `If-Match` header or one which matches `etag`.
any_match
rust
salvo-rs/salvo
crates/core/src/fs/named_file.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/fs/named_file.rs
Apache-2.0
fn none_match(etag: Option<&ETag>, req_headers: &HeaderMap) -> bool { match req_headers.typed_get::<IfNoneMatch>() { None => true, Some(if_none_match) => { if if_none_match == IfNoneMatch::any() { false } else if let Some(etag) = etag { if_none_match.precondition_passes(etag) } else { true } } } }
Returns true if `req_headers` doesn't have an `If-None-Match` header matching `req`.
none_match
rust
salvo-rs/salvo
crates/core/src/fs/named_file.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/fs/named_file.rs
Apache-2.0
pub fn tcp_idle_timeout(mut self, timeout: Duration) -> Self { self.tcp_idle_timeout = timeout; self }
Set the timeout for close the idle tcp connection.
tcp_idle_timeout
rust
salvo-rs/salvo
crates/core/src/fuse/flex.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/fuse/flex.rs
Apache-2.0
pub fn tcp_frame_timeout(mut self, timeout: Duration) -> Self { self.tcp_frame_timeout = timeout; self }
Set the timeout for close the connection if frame can not be recived.
tcp_frame_timeout
rust
salvo-rs/salvo
crates/core/src/fuse/flex.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/fuse/flex.rs
Apache-2.0
pub fn is_tcp(&self) -> bool { matches!(self, Self::Tcp) }
Check if the transport protocol is tcp.
is_tcp
rust
salvo-rs/salvo
crates/core/src/fuse/mod.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/fuse/mod.rs
Apache-2.0
pub fn is_quic(&self) -> bool { matches!(self, Self::Quic) }
Check if the transport protocol is quic.
is_quic
rust
salvo-rs/salvo
crates/core/src/fuse/mod.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/fuse/mod.rs
Apache-2.0
pub(crate) async fn read(headers: &HeaderMap, body: ReqBody) -> Result<FormData, ParseError> { let ctype: Option<Mime> = headers .get(CONTENT_TYPE) .and_then(|h| h.to_str().ok()) .and_then(|v| v.parse().ok()); match ctype { Some(ctype) if ctype.subtype() == mime::WWW_FORM_URLENCODED => { let data = BodyExt::collect(body) .await .map_err(ParseError::other)? .to_bytes(); let mut form_data = FormData::new(); form_data.fields = form_urlencoded::parse(&data).into_owned().collect(); Ok(form_data) } Some(ctype) if ctype.type_() == mime::MULTIPART => { let mut form_data = FormData::new(); if let Some(boundary) = headers .get(CONTENT_TYPE) .and_then(|ct| ct.to_str().ok()) .and_then(|ct| multer::parse_boundary(ct).ok()) { let body = body.map(|f| f.map(|f| f.into_data().unwrap_or_default())); let mut multipart = Multipart::new(body, boundary); while let Some(mut field) = multipart.next_field().await? { if let Some(name) = field.name().map(|s| s.to_owned()) { if field.headers().get(CONTENT_TYPE).is_some() { form_data .files .insert(name, FilePart::create(&mut field).await?); } else { form_data.fields.insert(name, field.text().await?); } } } } Ok(form_data) } _ => Err(ParseError::InvalidContentType), } }
Parse MIME `multipart/*` information from a stream as a `FormData`.
read
rust
salvo-rs/salvo
crates/core/src/http/form.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/form.rs
Apache-2.0
pub async fn create(field: &mut Field<'_>) -> Result<FilePart, ParseError> { // Setup a file to capture the contents. let mut path = tokio::task::spawn_blocking(|| Builder::new().prefix("salvo_http_multipart").tempdir()) .await .expect("Runtime spawn blocking poll error")? .keep(); let temp_dir = Some(path.clone()); let name = field.file_name().map(|s| s.to_owned()); path.push(format!( "{}.{}", text_nonce(), name.as_deref() .and_then(|name| { Path::new(name).extension().and_then(OsStr::to_str) }) .unwrap_or("unknown") )); let mut file = File::create(&path).await?; let mut size = 0; while let Some(chunk) = field.chunk().await? { size += chunk.len() as u64; file.write_all(&chunk).await?; } file.sync_all().await?; Ok(FilePart { name, headers: field.headers().to_owned(), path, size, temp_dir, }) }
Create a new temporary FilePart (when created this way, the file will be deleted once the FilePart object goes out of scope).
create
rust
salvo-rs/salvo
crates/core/src/http/form.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/form.rs
Apache-2.0
pub fn parse(header: &str, size: u64) -> Result<Vec<HttpRange>, ParseError> { if header.is_empty() { return Ok(Vec::new()); } if !header.starts_with(PREFIX) { return Err(ParseError::InvalidRange); } let size_sig = size as i64; let mut no_overlap = false; let all_ranges: Vec<Option<HttpRange>> = header[PREFIX_LEN..] .split(',') .map(|x| x.trim()) .filter(|x| !x.is_empty()) .map(|ra| { let mut start_end_iter = ra.split('-'); let start_str = start_end_iter.next().ok_or(())?.trim(); let end_str = start_end_iter.next().ok_or(())?.trim(); if start_str.is_empty() { // If no start is specified, end specifies the // range start relative to the end of the file. let mut length: i64 = end_str.parse().map_err(|_| ())?; if length > size_sig { length = size_sig; } Ok(Some(HttpRange { start: (size_sig - length) as u64, length: length as u64, })) } else { let start: i64 = start_str.parse().map_err(|_| ())?; if start < 0 { return Err(()); } if start >= size_sig { no_overlap = true; return Ok(None); } let length = if end_str.is_empty() { // If no end is specified, range extends to end of the file. size_sig - start } else { let mut end: i64 = end_str.parse().map_err(|_| ())?; if start > end { return Err(()); } if end >= size_sig { end = size_sig - 1; } end - start + 1 }; Ok(Some(HttpRange { start: start as u64, length: length as u64, })) } }) .collect::<Result<_, _>>() .map_err(|_| ParseError::InvalidRange)?; let ranges: Vec<HttpRange> = all_ranges.into_iter().flatten().collect(); if no_overlap && ranges.is_empty() { return Err(ParseError::InvalidRange); } Ok(ranges) }
Parses Range HTTP header string as per RFC 2616. `header` is HTTP Range header (e.g. `bytes=bytes=0-9`). `size` is full size of response (file).
parse
rust
salvo-rs/salvo
crates/core/src/http/range.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/range.rs
Apache-2.0
pub fn set_global_secure_max_size(size: usize) { let mut lock = GLOBAL_SECURE_MAX_SIZE.write(); *lock = size; }
Set secure maximum size globally. It is recommended to use the [`SecureMaxSize`] middleware to have finer-grained control over [`Request`]. **Note**: The security maximum value is only effective when directly obtaining data from the body. For uploaded files, the files are written to temporary files and the bytes is not directly obtained, so they will not be affected.
set_global_secure_max_size
rust
salvo-rs/salvo
crates/core/src/http/request.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/request.rs
Apache-2.0
pub fn from_hyper<B>(req: hyper::Request<B>, scheme: Scheme) -> Self where B: Into<ReqBody>, { let ( http::request::Parts { method, uri, version, headers, extensions, .. }, body, ) = req.into_parts(); // Set the request cookies, if they exist. #[cfg(feature = "cookie")] let cookies = { let mut cookie_jar = CookieJar::new(); for header in headers.get_all(http::header::COOKIE) { if let Ok(header) = header.to_str() { for cookie_str in header.split(';').map(|s| s.trim()) { if let Ok(cookie) = Cookie::parse_encoded(cookie_str).map(|c| c.into_owned()) { cookie_jar.add_original(cookie); } } } } cookie_jar }; Request { queries: OnceLock::new(), uri, headers, body: body.into(), extensions, method, #[cfg(feature = "cookie")] cookies, // accept: None, params: PathParams::new(), form_data: tokio::sync::OnceCell::new(), payload: tokio::sync::OnceCell::new(), // multipart: OnceLock::new(), local_addr: SocketAddr::Unknown, remote_addr: SocketAddr::Unknown, version, scheme, secure_max_size: None, #[cfg(feature = "matched-path")] matched_path: Default::default(), } }
Creates a new `Request` from [`hyper::Request`].
from_hyper
rust
salvo-rs/salvo
crates/core/src/http/request.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/request.rs
Apache-2.0
pub fn add_header<N, V>( &mut self, name: N, value: V, overwrite: bool, ) -> crate::Result<&mut Self> where N: IntoHeaderName, V: TryInto<HeaderValue>, { let value = value .try_into() .map_err(|_| Error::Other("invalid header value".into()))?; if overwrite { self.headers.insert(name, value); } else { self.headers.append(name, value); } Ok(self) }
Modify a header for this request. When `overwrite` is set to `true`, If the header is already present, the value will be replaced. When `overwrite` is set to `false`, The new header is always appended to the request, even if the header already exists.
add_header
rust
salvo-rs/salvo
crates/core/src/http/request.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/request.rs
Apache-2.0
pub fn set_secure_max_size(&mut self, size: usize) { self.secure_max_size = Some(size); }
Set secure max size, default value is 64KB.
set_secure_max_size
rust
salvo-rs/salvo
crates/core/src/http/request.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/request.rs
Apache-2.0
pub async fn parse_body_with_max_size<'de, T>(&'de mut self, max_size: usize) -> ParseResult<T> where T: Deserialize<'de>, { if let Some(ctype) = self.content_type() { if ctype.subtype() == mime::WWW_FORM_URLENCODED || ctype.subtype() == mime::FORM_DATA { return from_str_multi_map(self.form_data().await?.fields.iter_all()) .map_err(ParseError::Deserialize); } else if ctype.subtype() == mime::JSON { return self.payload_with_max_size(max_size).await.and_then(|body| { serde_json::from_slice::<T>(body).map_err(ParseError::SerdeJson) }); } } Err(ParseError::InvalidContentType) }
Parse json body or form body as type `T` from request with max size.
parse_body_with_max_size
rust
salvo-rs/salvo
crates/core/src/http/request.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/request.rs
Apache-2.0
pub fn add_header<N, V>( &mut self, name: N, value: V, overwrite: bool, ) -> crate::Result<&mut Self> where N: IntoHeaderName, V: TryInto<HeaderValue>, { let value = value .try_into() .map_err(|_| Error::Other("invalid header value".into()))?; if overwrite { self.headers.insert(name, value); } else { self.headers.append(name, value); } Ok(self) }
Modify a header for this response. When `overwrite` is set to `true`, If the header is already present, the value will be replaced. When `overwrite` is set to `false`, The new header is always appended to the request, even if the header already exists.
add_header
rust
salvo-rs/salvo
crates/core/src/http/response.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/response.rs
Apache-2.0
pub fn render<P>(&mut self, scribe: P) where P: Scribe, { scribe.render(self); }
Render content. # Example ``` use salvo_core::http::{Response, StatusCode}; let mut res = Response::new(); res.render("hello world"); ```
render
rust
salvo-rs/salvo
crates/core/src/http/response.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/response.rs
Apache-2.0
pub async fn send_file<P>(&mut self, path: P, req_headers: &HeaderMap) where P: Into<PathBuf> + Send, { let path = path.into(); if !path.exists() { self.render(StatusError::not_found()); } else { match NamedFile::builder(path).build().await { Ok(file) => file.send(req_headers, self).await, Err(_) => self.render(StatusError::internal_server_error()), } } }
Attempts to send a file. If file not exists, not found error will occur. If you want more settings, you can use `NamedFile::builder` to create a new [`NamedFileBuilder`](crate::fs::NamedFileBuilder).
send_file
rust
salvo-rs/salvo
crates/core/src/http/response.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/response.rs
Apache-2.0
pub fn write_body(&mut self, data: impl Into<Bytes>) -> crate::Result<()> { match self.body_mut() { ResBody::None => { self.body = ResBody::Once(data.into()); } ResBody::Once(bytes) => { let mut chunks = VecDeque::new(); chunks.push_back(bytes.clone()); chunks.push_back(data.into()); self.body = ResBody::Chunks(chunks); } ResBody::Chunks(chunks) => { chunks.push_back(data.into()); } ResBody::Hyper(_) => { tracing::error!( "current body's kind is `ResBody::Hyper`, it is not allowed to write bytes" ); return Err(Error::other( "current body's kind is `ResBody::Hyper`, it is not allowed to write bytes", )); } ResBody::Boxed(_) => { tracing::error!( "current body's kind is `ResBody::Boxed`, it is not allowed to write bytes" ); return Err(Error::other( "current body's kind is `ResBody::Boxed`, it is not allowed to write bytes", )); } ResBody::Stream(_) => { tracing::error!( "current body's kind is `ResBody::Stream`, it is not allowed to write bytes" ); return Err(Error::other( "current body's kind is `ResBody::Stream`, it is not allowed to write bytes", )); } ResBody::Channel { .. } => { tracing::error!( "current body's kind is `ResBody::Channel`, it is not allowed to write bytes" ); return Err(Error::other( "current body's kind is `ResBody::Channel`, it is not allowed to write bytes", )); } ResBody::Error(_) => { self.body = ResBody::Once(data.into()); } } Ok(()) }
Write bytes data to body. If body is none, a new `ResBody` will created.
write_body
rust
salvo-rs/salvo
crates/core/src/http/response.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/response.rs
Apache-2.0
pub(crate) fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<IoResult<()>> { self.data_tx .poll_ready(cx) .map_err(|e| IoError::other(format!("failed to poll ready: {e}"))) }
Check to see if this `Sender` can send more data.
poll_ready
rust
salvo-rs/salvo
crates/core/src/http/body/channel.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/body/channel.rs
Apache-2.0
pub async fn send_data(&mut self, chunk: impl Into<Bytes> + Send) -> IoResult<()> { self.ready().await?; self.data_tx .try_send(Ok(chunk.into())) .map_err(|e| IoError::other(format!("failed to send data: {e}"))) }
Send data on data channel when it is ready.
send_data
rust
salvo-rs/salvo
crates/core/src/http/body/channel.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/body/channel.rs
Apache-2.0
pub fn is_error(&self) -> bool { matches!(*self, Self::Error(_)) }
Check is that body is error will be process in catcher.
is_error
rust
salvo-rs/salvo
crates/core/src/http/body/res.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/body/res.rs
Apache-2.0
pub fn stream<S, O, E>(stream: S) -> Self where S: Stream<Item = Result<O, E>> + Send + 'static, O: Into<BytesFrame> + 'static, E: Into<BoxedError> + 'static, { let mapped = stream.map_ok(Into::into).map_err(Into::into); Self::Stream(SyncWrapper::new(Box::pin(mapped))) }
Wrap a futures `Stream` in a box inside `Body`.
stream
rust
salvo-rs/salvo
crates/core/src/http/body/res.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/body/res.rs
Apache-2.0
pub fn channel() -> (BodySender, Self) { let (data_tx, data_rx) = mpsc::channel(0); let (trailers_tx, trailers_rx) = oneshot::channel(); let tx = BodySender { data_tx, trailers_tx: Some(trailers_tx), }; let rx = ResBody::Channel(BodyReceiver { data_rx, trailers_rx, }); (tx, rx) }
Create a `Body` stream with an associated sender half. Useful when wanting to stream chunks from another thread.
channel
rust
salvo-rs/salvo
crates/core/src/http/body/res.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/body/res.rs
Apache-2.0
pub fn brief(mut self, brief: impl Into<String>) -> Self { self.brief = brief.into(); self }
Sets brief field and returns `Self`.
brief
rust
salvo-rs/salvo
crates/core/src/http/errors/status_error.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/errors/status_error.rs
Apache-2.0
pub fn detail(mut self, detail: impl Into<String>) -> Self { self.detail = Some(detail.into()); self }
Sets detail field and returns `Self`.
detail
rust
salvo-rs/salvo
crates/core/src/http/errors/status_error.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/errors/status_error.rs
Apache-2.0
pub fn cause<T>(mut self, cause: T) -> Self where T: Into<Box<dyn StdError + Sync + Send + 'static>>, { self.cause = Some(cause.into()); self }
Sets cause field and returns `Self`.
cause
rust
salvo-rs/salvo
crates/core/src/http/errors/status_error.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/errors/status_error.rs
Apache-2.0
pub fn origin<T: Send + Sync + 'static>(mut self, origin: T) -> Self { self.origin = Some(Box::new(origin)); self }
Sets origin field and returns `Self`.
origin
rust
salvo-rs/salvo
crates/core/src/http/errors/status_error.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/errors/status_error.rs
Apache-2.0
pub fn from_code(code: StatusCode) -> Option<StatusError> { match code { StatusCode::BAD_REQUEST => Some(StatusError::bad_request()), StatusCode::UNAUTHORIZED => Some(StatusError::unauthorized()), StatusCode::PAYMENT_REQUIRED => Some(StatusError::payment_required()), StatusCode::FORBIDDEN => Some(StatusError::forbidden()), StatusCode::NOT_FOUND => Some(StatusError::not_found()), StatusCode::METHOD_NOT_ALLOWED => Some(StatusError::method_not_allowed()), StatusCode::NOT_ACCEPTABLE => Some(StatusError::not_acceptable()), StatusCode::PROXY_AUTHENTICATION_REQUIRED => { Some(StatusError::proxy_authentication_required()) } StatusCode::REQUEST_TIMEOUT => Some(StatusError::request_timeout()), StatusCode::CONFLICT => Some(StatusError::conflict()), StatusCode::GONE => Some(StatusError::gone()), StatusCode::LENGTH_REQUIRED => Some(StatusError::length_required()), StatusCode::PRECONDITION_FAILED => Some(StatusError::precondition_failed()), StatusCode::PAYLOAD_TOO_LARGE => Some(StatusError::payload_too_large()), StatusCode::URI_TOO_LONG => Some(StatusError::uri_too_long()), StatusCode::UNSUPPORTED_MEDIA_TYPE => Some(StatusError::unsupported_media_type()), StatusCode::RANGE_NOT_SATISFIABLE => Some(StatusError::range_not_satisfiable()), StatusCode::EXPECTATION_FAILED => Some(StatusError::expectation_failed()), StatusCode::IM_A_TEAPOT => Some(StatusError::im_a_teapot()), StatusCode::MISDIRECTED_REQUEST => Some(StatusError::misdirected_request()), StatusCode::UNPROCESSABLE_ENTITY => Some(StatusError::unprocessable_entity()), StatusCode::LOCKED => Some(StatusError::locked()), StatusCode::FAILED_DEPENDENCY => Some(StatusError::failed_dependency()), StatusCode::UPGRADE_REQUIRED => Some(StatusError::upgrade_required()), StatusCode::PRECONDITION_REQUIRED => Some(StatusError::precondition_required()), StatusCode::TOO_MANY_REQUESTS => Some(StatusError::too_many_requests()), StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE => { Some(StatusError::request_header_fields_toolarge()) } StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS => { Some(StatusError::unavailable_for_legalreasons()) } StatusCode::INTERNAL_SERVER_ERROR => Some(StatusError::internal_server_error()), StatusCode::NOT_IMPLEMENTED => Some(StatusError::not_implemented()), StatusCode::BAD_GATEWAY => Some(StatusError::bad_gateway()), StatusCode::SERVICE_UNAVAILABLE => Some(StatusError::service_unavailable()), StatusCode::GATEWAY_TIMEOUT => Some(StatusError::gateway_timeout()), StatusCode::HTTP_VERSION_NOT_SUPPORTED => { Some(StatusError::http_version_not_supported()) } StatusCode::VARIANT_ALSO_NEGOTIATES => Some(StatusError::variant_also_negotiates()), StatusCode::INSUFFICIENT_STORAGE => Some(StatusError::insufficient_storage()), StatusCode::LOOP_DETECTED => Some(StatusError::loop_detected()), StatusCode::NOT_EXTENDED => Some(StatusError::not_extended()), StatusCode::NETWORK_AUTHENTICATION_REQUIRED => { Some(StatusError::network_authentication_required()) } _ => None, } }
Create new `StatusError` with code. If code is not error, it will be `None`.
from_code
rust
salvo-rs/salvo
crates/core/src/http/errors/status_error.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/http/errors/status_error.rs
Apache-2.0
pub fn tail(&self) -> Option<&str> { if self.greedy { self.inner.last().map(|(_, v)| &**v) } else { None } }
Get the last param starts with '*', for example: <**rest>, <*?rest>.
tail
rust
salvo-rs/salvo
crates/core/src/routing/path_params.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/routing/path_params.rs
Apache-2.0
pub async fn detect( &self, req: &mut Request, path_state: &mut PathState, ) -> Option<DetectMatched> { Box::pin(async move { for filter in &self.filters { if !filter.filter(req, path_state).await { return None; } } if !self.routers.is_empty() { let original_cursor = path_state.cursor; #[cfg(feature = "matched-path")] let original_matched_parts_len = path_state.matched_parts.len(); for child in &self.routers { if let Some(dm) = child.detect(req, path_state).await { return Some(DetectMatched { hoops: [&self.hoops[..], &dm.hoops[..]].concat(), goal: dm.goal.clone(), }); } else { #[cfg(feature = "matched-path")] path_state .matched_parts .truncate(original_matched_parts_len); path_state.cursor = original_cursor; } } } if path_state.is_ended() { path_state.once_ended = true; if let Some(goal) = &self.goal { return Some(DetectMatched { hoops: self.hoops.clone(), goal: goal.clone(), }); } } None }) .await }
Detect current router is matched for current request.
detect
rust
salvo-rs/salvo
crates/core/src/routing/router.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/routing/router.rs
Apache-2.0
pub fn lack(mut self, lack: bool) -> Self { self.lack = lack; self }
Set lack value and return `Self`.
lack
rust
salvo-rs/salvo
crates/core/src/routing/filters/others.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/routing/filters/others.rs
Apache-2.0
pub fn lack(mut self, lack: bool) -> Self { self.lack = lack; self }
Set lack value and return `Self`.
lack
rust
salvo-rs/salvo
crates/core/src/routing/filters/others.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/routing/filters/others.rs
Apache-2.0
pub fn lack(mut self, lack: bool) -> Self { self.lack = lack; self }
Set lack value and return `Self`.
lack
rust
salvo-rs/salvo
crates/core/src/routing/filters/others.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/routing/filters/others.rs
Apache-2.0
pub fn new(wisps: Vec<WispKind>) -> Result<Self, String> { let mut comb_regex = "^".to_owned(); let mut names = Vec::with_capacity(wisps.len()); let mut is_prev_named = false; let mut is_greedy = false; let mut wild_start = None; let mut wild_regex = None; let any_chars_regex = Regex::new(".*").expect("regex should worked"); for wisp in wisps { match wisp { WispKind::Const(wisp) => { if is_greedy { return Err(format!( "ConstWisp `{}` follows a greedy wisp in CombWisp", wisp.0 )); } is_prev_named = false; comb_regex.push_str(&regex::escape(&wisp.0)) } WispKind::Named(wisp) => { if is_greedy { return Err(format!( "NamedWisp `{}` follows a greedy wisp in CombWisp", wisp.0 )); } if is_prev_named { return Err(format!( "NamedWisp `{}` should not be added after another NamedWisp when it is CombWisp's children", wisp.0 )); } is_prev_named = true; if wisp.0.starts_with('*') { is_greedy = true; let (star_mark, name) = crate::routing::split_wild_name(&wisp.0); wild_regex = Some(any_chars_regex.clone()); wild_start = Some(star_mark.to_owned()); names.push(name.to_owned()); } else { comb_regex.push_str(&format!("(?<{}>.*)", &regex::escape(&wisp.0))); names.push(wisp.0); } } WispKind::Regex(wisp) => { if is_greedy { return Err(format!( "RegexWisp `{}` follows a greedy wisp in CombWisp", wisp.name )); } is_prev_named = false; if wisp.name.starts_with('*') { is_greedy = true; let (star_mark, name) = crate::routing::split_wild_name(&wisp.name); wild_regex = Some(wisp.regex); wild_start = Some(star_mark.to_owned()); names.push(name.to_owned()); } else { let regex = wisp .regex .as_str() .trim_start_matches('^') .trim_end_matches('$'); comb_regex.push_str(&format!("(?<{}>{})", wisp.name, regex)); names.push(wisp.name); } } WispKind::Chars(wisp) => { return Err(format!( "unsupported CharsWisp `{}` add to CombWisp", wisp.name )); } _ => { return Err(format!("unsupported wisp: {wisp:?} add to CombWisp")); } } } if wild_regex.is_none() { comb_regex.push('$'); } Regex::new(&comb_regex) .map(|comb_regex| Self { names, comb_regex, wild_regex, wild_start, }) .map_err(|e| format!("Regex error: {e}")) }
Create new `CombWisp`. # Panics If contains unsupported `WispKind``.
new
rust
salvo-rs/salvo
crates/core/src/routing/filters/path.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/routing/filters/path.rs
Apache-2.0
pub fn detect(&self, state: &mut PathState) -> bool { let original_cursor = state.cursor; for ps in &self.path_wisps { let row = state.cursor.0; if ps.detect(state) { if row == state.cursor.0 && row != state.parts.len() { state.cursor = original_cursor; return false; } } else { state.cursor = original_cursor; return false; } } true }
Detect is that path is match.
detect
rust
salvo-rs/salvo
crates/core/src/routing/filters/path.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/routing/filters/path.rs
Apache-2.0
pub fn get(url: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(url, Method::GET) }
Create a new `RequestBuilder` with the GET method and this TestClient's settings applied on it.
get
rust
salvo-rs/salvo
crates/core/src/test/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/client.rs
Apache-2.0
pub fn post(url: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(url, Method::POST) }
Create a new `RequestBuilder` with the POST method and this TestClient's settings applied on it.
post
rust
salvo-rs/salvo
crates/core/src/test/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/client.rs
Apache-2.0
pub fn put(url: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(url, Method::PUT) }
Create a new `RequestBuilder` with the PUT method and this TestClient's settings applied on it.
put
rust
salvo-rs/salvo
crates/core/src/test/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/client.rs
Apache-2.0
pub fn delete(url: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(url, Method::DELETE) }
Create a new `RequestBuilder` with the DELETE method and this TestClient's settings applied on it.
delete
rust
salvo-rs/salvo
crates/core/src/test/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/client.rs
Apache-2.0
pub fn head(url: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(url, Method::HEAD) }
Create a new `RequestBuilder` with the HEAD method and this TestClient's settings applied on it.
head
rust
salvo-rs/salvo
crates/core/src/test/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/client.rs
Apache-2.0
pub fn options(url: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(url, Method::OPTIONS) }
Create a new `RequestBuilder` with the OPTIONS method and this TestClient's settings applied on it.
options
rust
salvo-rs/salvo
crates/core/src/test/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/client.rs
Apache-2.0
pub fn patch(url: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(url, Method::PATCH) }
Create a new `RequestBuilder` with the PATCH method and this TestClient's settings applied on it.
patch
rust
salvo-rs/salvo
crates/core/src/test/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/client.rs
Apache-2.0
pub fn trace(url: impl AsRef<str>) -> RequestBuilder { RequestBuilder::new(url, Method::TRACE) }
Create a new `RequestBuilder` with the TRACE method and this TestClient's settings applied on it.
trace
rust
salvo-rs/salvo
crates/core/src/test/client.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/client.rs
Apache-2.0
pub fn new<U>(url: U, method: Method) -> Self where U: AsRef<str>, { let url = Url::parse(url.as_ref()).expect("invalid url"); Self { url, method, headers: HeaderMap::new(), // params: HeaderMap::new(), body: ReqBody::None, } }
Create a new `RequestBuilder` with the base URL and the given method. # Panics Panics if the base url is invalid or if the method is CONNECT.
new
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn query<K, V>(mut self, key: K, value: V) -> Self where K: AsRef<str>, V: ToString, { self.url.query_pairs_mut().append_pair(key.as_ref(), &value.to_string()); self }
Associate a query string parameter to the given value. The same key can be used multiple times.
query
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn queries<P, K, V>(mut self, pairs: P) -> Self where P: IntoIterator, P::Item: Borrow<(K, V)>, K: AsRef<str>, V: ToString, { for pair in pairs.into_iter() { let (key, value) = pair.borrow(); self.url.query_pairs_mut().append_pair(key.as_ref(), &value.to_string()); } self }
Associated a list of pairs to query parameters. The same key can be used multiple times. # Example ```ignore TestClient::get("http://foo.bar").queries(&[("p1", "v1"), ("p2", "v2")]); ```
queries
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn body(mut self, body: impl Into<ReqBody>) -> Self { self.body = body.into(); self }
Sets the body of this request.
body
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn text(mut self, body: impl Into<String>) -> Self { self.headers .entry(header::CONTENT_TYPE) .or_insert(HeaderValue::from_static("text/plain; charset=utf-8")); self.body(body.into()) }
Sets the body of this request to be text. If the `Content-Type` header is unset, it will be set to `text/plain` and the charset to UTF-8.
text
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn bytes(mut self, body: Vec<u8>) -> Self { self.headers .entry(header::CONTENT_TYPE) .or_insert(HeaderValue::from_static("application/octet-stream")); self.body(body) }
Sets the body of this request to be bytes. If the `Content-Type` header is unset, it will be set to `application/octet-stream`.
bytes
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn json<T: serde::Serialize>(mut self, value: &T) -> Self { self.headers .entry(header::CONTENT_TYPE) .or_insert(HeaderValue::from_static("application/json; charset=utf-8")); self.body(serde_json::to_vec(value).expect("Failed to serialize json.")) }
Sets the body of this request to be the JSON representation of the given object. If the `Content-Type` header is unset, it will be set to `application/json` and the charset to UTF-8.
json
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn raw_json(mut self, value: impl Into<String>) -> Self { self.headers .entry(header::CONTENT_TYPE) .or_insert(HeaderValue::from_static("application/json; charset=utf-8")); self.body(value.into()) }
Sets the body of this request to be the JSON representation of the given string. If the `Content-Type` header is unset, it will be set to `application/json` and the charset to UTF-8.
raw_json
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn form<T: serde::Serialize>(mut self, value: &T) -> Self { let body = serde_urlencoded::to_string(value) .expect("`serde_urlencoded::to_string` returns error") .into_bytes(); self.headers .entry(header::CONTENT_TYPE) .or_insert(HeaderValue::from_static("application/x-www-form-urlencoded")); self.body(body) }
Sets the body of this request to be the URL-encoded representation of the given object. If the `Content-Type` header is unset, it will be set to `application/x-www-form-urlencoded`.
form
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn raw_form(mut self, value: impl Into<String>) -> Self { self.headers .entry(header::CONTENT_TYPE) .or_insert(HeaderValue::from_static("application/x-www-form-urlencoded")); self.body(value.into()) }
Sets the body of this request to be the URL-encoded representation of the given string. If the `Content-Type` header is unset, it will be set to `application/x-www-form-urlencoded`.
raw_form
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub fn add_header<N, V>(mut self, name: N, value: V, overwrite: bool) -> Self where N: IntoHeaderName, V: TryInto<HeaderValue>, { let value = value .try_into() .map_err(|_| Error::Other("invalid header value".into())) .expect("invalid header value"); if overwrite { self.headers.insert(name, value); } else { self.headers.append(name, value); } self }
Modify a header for this response. When `overwrite` is set to `true`, If the header is already present, the value will be replaced. When `overwrite` is set to `false`, The new header is always appended to the request, even if the header already exists.
add_header
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0
pub async fn send(self, target: impl SendTarget + Send) -> Response { #[cfg(feature = "cookie")] { let mut response = target.call(self.build()).await; let values = response .cookies .delta() .filter_map(|c| c.encoded().to_string().parse().ok()) .collect::<Vec<_>>(); for hv in values { response.headers_mut().insert(header::SET_COOKIE, hv); } response } #[cfg(not(feature = "cookie"))] target.call(self.build()).await }
Send request to target, such as [`Router`], [`Service`], [`Handler`].
send
rust
salvo-rs/salvo
crates/core/src/test/request/builder.rs
https://github.com/salvo-rs/salvo/blob/master/crates/core/src/test/request/builder.rs
Apache-2.0