Skip to main content

Context

Struct Context 

Source
pub struct Context {
    pub req: Request,
    /* private fields */
}
Expand description

Context holds request data and provides response building methods

Fields§

§req: Request

Implementations§

Source§

impl Context

Source

pub async fn new(req: HyperRequest<Incoming>, params: Params) -> Result<Self>

Create a new context from a request and params

Source

pub async fn set(&self, key: impl Into<String>, value: impl Into<String>)

Set a value in the context state (shared between middleware)

Source

pub async fn get(&self, key: &str) -> Option<String>

Get a value from the context state

Source

pub fn cookie(&self, name: &str) -> Option<String>

Read a request cookie by name.

Source

pub fn cookies(&self) -> HashMap<String, String>

All request cookies.

Queue a Set-Cookie for the response. Errors if the cookie is invalid.

Queue a deletion of the named cookie (Max-Age=0).

Source

pub fn peer_addr(&self) -> Option<SocketAddr>

The peer address of the underlying connection, if known. This is the direct socket peer — for the originating client behind a proxy, use client_ip.

Source

pub fn client_ip(&self) -> Option<IpAddr>

Best-effort originating client IP.

When proxy trust is enabled (app.trust_proxy(true)) this honors the left-most X-Forwarded-For entry, then Forwarded: for=…; otherwise (or if no such header) it falls back to the connection peer. Only enable proxy trust when the app is actually behind a trusted proxy — these headers are client-spoofable.

Source

pub async fn status(&self, code: u16)

Set the response status code

Source

pub async fn header(&self, name: impl Into<String>, value: impl Into<String>)

Add a response header

Source

pub async fn json<T: Serialize>(&self, value: T) -> Result<Response>

Return a JSON response

Source

pub async fn text(&self, text: impl Into<String>) -> Result<Response>

Return a text response

Source

pub async fn html(&self, html: impl Into<String>) -> Result<Response>

Return an HTML response

Source

pub async fn stream<S>(&self, body: S) -> Result<Response>
where S: Stream<Item = Result<Bytes, BoxError>> + Send + 'static,

Return a streaming response body.

Each Ok(bytes) item is sent as a chunk; the response is chunked (no Content-Length). Any queued header/status set on the context is applied, except Content-Length/Transfer-Encoding (which would conflict with the chunked framing and are dropped). If no Content-Type was set, it defaults to application/octet-stream. An Err(_) item aborts the connection.

let chunks: Vec<std::result::Result<Bytes, BoxError>> = vec![Ok(Bytes::from("hi"))];
ctx.stream(futures_util::stream::iter(chunks)).await
Source

pub async fn sse<S>(&self, events: S) -> Result<Response>
where S: Stream<Item = SseEvent> + Send + 'static,

Return a Server-Sent Events response streaming typed events.

Sets Content-Type: text/event-stream, Cache-Control: no-cache, and X-Accel-Buffering: no, then streams each SseEvent encoded to the SSE wire format (chunked, no Content-Length).

let evs = vec![SseEvent::new(&json!({ "hello": "world" }))?];
ctx.sse(futures_util::stream::iter(evs)).await
Source

pub async fn sse_keep_alive<S>( &self, events: S, interval: Duration, ) -> Result<Response>
where S: Stream<Item = SseEvent> + Send + 'static,

Like sse, but injects a : ping comment whenever the event stream is idle for interval, so proxies and idle connections aren’t dropped. Terminates when the event stream ends.

Source

pub fn last_event_id(&self) -> Option<String>

The Last-Event-ID request header, if present, for app-driven resume.

Source

pub async fn redirect(&self, location: &str) -> Result<Response>

Return a redirect response

Source

pub async fn not_found(&self) -> Result<Response>

Return a not found response

Trait Implementations§

Source§

impl Clone for Context

Source§

fn clone(&self) -> Context

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl FromRequest for Context

The full request context — the identity extractor, so existing |ctx: Context| async move { … } handlers keep working unchanged.

Source§

fn from_request<'life0, 'async_trait>( ctx: &'life0 Context, ) -> Pin<Box<dyn Future<Output = Result<Self>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more