Context

Struct Context 

Source
pub struct Context<S = ()> {
    pub req: Request,
    pub resp: Response,
    pub exec: Executor,
    pub remote_addr: SocketAddr,
    /* private fields */
}
Expand description

A structure to share request, response and other data between middlewares.

§Example

use roa_core::{App, Context, Next, Result};
use tracing::info;
use tokio::fs::File;

let app = App::new().gate(gate).end(end);
async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    info!("{} {}", ctx.method(), ctx.uri());
    next.await
}

async fn end(ctx: &mut Context) -> Result {
    ctx.resp.write_reader(File::open("assets/welcome.html").await?);
    Ok(())
}

Fields§

§req: Request

The request, to read http method, uri, version, headers and body.

§resp: Response

The response, to set http status, version, headers and body.

§exec: Executor

The executor, to spawn futures or blocking works.

§remote_addr: SocketAddr

Socket addr of last client or proxy.

Implementations§

Source§

impl<S> Context<S>

Source

pub fn uri(&self) -> &Uri

Clone URI.

§Example
use roa_core::{App, Context, Result};

let app = App::new().end(get);

async fn get(ctx: &mut Context) -> Result {
    assert_eq!("/", ctx.uri().to_string());
    Ok(())
}
Source

pub fn method(&self) -> &Method

Clone request::method.

§Example
use roa_core::{App, Context, Result};
use roa_core::http::Method;

let app = App::new().end(get);

async fn get(ctx: &mut Context) -> Result {
    assert_eq!(Method::GET, ctx.method());
    Ok(())
}
Source

pub fn get(&self, name: impl AsHeaderName) -> Option<&str>

Search for a header value and try to get its string reference.

§Example
use roa_core::{App, Context, Result};
use roa_core::http::header::CONTENT_TYPE;

let app = App::new().end(get);

async fn get(ctx: &mut Context) -> Result {
    assert_eq!(
        Some("text/plain"),
        ctx.get(CONTENT_TYPE),
    );
    Ok(())
}
Source

pub fn must_get(&self, name: impl AsHeaderName) -> Result<&str>

Search for a header value and get its string reference.

Otherwise return a 400 BAD REQUEST.

§Example
use roa_core::{App, Context, Result};
use roa_core::http::header::CONTENT_TYPE;

let app = App::new().end(get);

async fn get(ctx: &mut Context) -> Result {
    assert_eq!(
        "text/plain",
        ctx.must_get(CONTENT_TYPE)?,
    );
    Ok(())
}
Source

pub fn status(&self) -> StatusCode

Clone response::status.

§Example
use roa_core::{App, Context, Result};
use roa_core::http::StatusCode;

let app = App::new().end(get);

async fn get(ctx: &mut Context) -> Result {
    assert_eq!(StatusCode::OK, ctx.status());
    Ok(())
}
Source

pub fn version(&self) -> Version

Clone request::version.

§Example
use roa_core::{App, Context, Result};
use roa_core::http::Version;

let app = App::new().end(get);

async fn get(ctx: &mut Context) -> Result {
    assert_eq!(Version::HTTP_11, ctx.version());
    Ok(())
}
Source

pub fn store_scoped<SC, K, V>( &mut self, scope: SC, key: K, value: V, ) -> Option<Arc<V>>
where SC: Any, K: Into<Cow<'static, str>>, V: Value,

Store key-value pair in specific scope.

§Example
use roa_core::{App, Context, Result, Next};

struct Scope;
struct AnotherScope;

async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    ctx.store_scoped(Scope, "id", "1".to_string());
    next.await
}

async fn end(ctx: &mut Context) -> Result {
    assert_eq!(1, ctx.load_scoped::<Scope, String>("id").unwrap().parse::<i32>()?);
    assert!(ctx.load_scoped::<AnotherScope, String>("id").is_none());
    Ok(())
}

let app = App::new().gate(gate).end(end);
Source

pub fn store<K, V>(&mut self, key: K, value: V) -> Option<Arc<V>>
where K: Into<Cow<'static, str>>, V: Value,

Store key-value pair in public scope.

§Example
use roa_core::{App, Context, Result, Next};

async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    ctx.store("id", "1".to_string());
    next.await
}

async fn end(ctx: &mut Context) -> Result {
    assert_eq!(1, ctx.load::<String>("id").unwrap().parse::<i32>()?);
    Ok(())
}

let app = App::new().gate(gate).end(end);
Source

pub fn load_scoped<'a, SC, V>(&self, key: &'a str) -> Option<Variable<'a, V>>
where SC: Any, V: Value,

Search for value by key in specific scope.

§Example
use roa_core::{App, Context, Result, Next};

struct Scope;

async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    ctx.store_scoped(Scope, "id", "1".to_owned());
    next.await
}

async fn end(ctx: &mut Context) -> Result {
    assert_eq!(1, ctx.load_scoped::<Scope, String>("id").unwrap().parse::<i32>()?);
    Ok(())
}

let app = App::new().gate(gate).end(end);
Source

pub fn load<'a, V>(&self, key: &'a str) -> Option<Variable<'a, V>>
where V: Value,

Search for value by key in public scope.

§Example
use roa_core::{App, Context, Result, Next};

async fn gate(ctx: &mut Context, next: Next<'_>) -> Result {
    ctx.store("id", "1".to_string());
    next.await
}

async fn end(ctx: &mut Context) -> Result {
    assert_eq!(1, ctx.load::<String>("id").unwrap().parse::<i32>()?);
    Ok(())
}

let app = App::new().gate(gate).end(end);

Trait Implementations§

Source§

impl<S: Clone> Clone for Context<S>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<S> Deref for Context<S>

Source§

type Target = S

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl<S> DerefMut for Context<S>

Source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.

Auto Trait Implementations§

§

impl<S = ()> !Freeze for Context<S>

§

impl<S = ()> !RefUnwindSafe for Context<S>

§

impl<S> Send for Context<S>
where S: Send,

§

impl<S> Sync for Context<S>
where S: Sync,

§

impl<S> Unpin for Context<S>
where S: Unpin,

§

impl<S = ()> !UnwindSafe for Context<S>

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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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 = Infallible

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
Source§

impl<T> State for T
where T: 'static + Clone + Send + Sync,