Struct roa::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

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(())
}

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(())
}

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(())
}

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(())
}

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(())
}

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(())
}

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);

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);

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);

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

Returns a copy of the value. Read more

Performs copy-assignment from source. Read more

Must get a cookie, throw 401 UNAUTHORIZED if it not exists.

Try to get a cookie, return None if it not exists. Read more

Set a cookie in pecent encoding, should not return Err. Read more

The resulting type after dereferencing.

Dereferences the value.

Mutably dereferences the value.

Get true host. Read more

Get true client ip. Read more

Get true forwarded ips. Read more

Try to get forwarded proto. Read more

Deserialize claims from token.

Verify token and deserialize claims with a validation. Use this method if this validation is different from that one of JwtGuard. Read more

read request body as Bytes.

This is supported on crate feature json only.

read request body as “json”.

This is supported on crate feature urlencoded only.

read request body as “urlencoded form”.

This is supported on crate feature multipart only.

read request body as “multipart form”.

This is supported on crate feature json only.

write object to response body as “application/json”

This is supported on crate feature template only.

write object to response body as “text/html; charset=utf-8”

write object to response body as “text/plain”

write object to response body as “application/octet-stream”

This is supported on crate feature file only.

write object to response body as extension name of file

Must get a variable, throw 400 BAD_REQUEST if it not exists. Read more

Query a variable, return None if it not exists. Read more

Must get a router parameter, throw 500 INTERNAL SERVER ERROR if it not exists.

Try to get a router parameter, return None if it not exists. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more

Immutably borrows from an owned value. Read more

Mutably borrows from an owned value. Read more

Converts self into T using Into<T>. Read more

Converts self into a target type. Read more

Causes self to use its Binary implementation when Debug-formatted.

Causes self to use its Display implementation when Debug-formatted. Read more

Causes self to use its LowerExp implementation when Debug-formatted. Read more

Causes self to use its LowerHex implementation when Debug-formatted. Read more

Causes self to use its Octal implementation when Debug-formatted.

Causes self to use its Pointer implementation when Debug-formatted. Read more

Causes self to use its UpperExp implementation when Debug-formatted. Read more

Causes self to use its UpperHex implementation when Debug-formatted. Read more

Performs the conversion.

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

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

Performs the conversion.

Pipes by value. This is generally the method you want to use. Read more

Borrows self and passes that borrow into the pipe function. Read more

Mutably borrows self and passes that borrow into the pipe function. Read more

Borrows self, then passes self.borrow() into the pipe function. Read more

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more

Borrows self, then passes self.as_ref() into the pipe function.

Mutably borrows self, then passes self.as_mut() into the pipe function. Read more

Borrows self, then passes self.deref() into the pipe function.

Mutably borrows self, then passes self.deref_mut() into the pipe function. Read more

Pipes a value into a function that cannot ordinarily be called in suffix position. Read more

Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait borrow into a function that cannot normally be called in suffix position. Read more

Pipes a trait mutable borrow into a function that cannot normally be called in suffix position. Read more

Pipes a dereference into a function that cannot normally be called in suffix position. Read more

Pipes a mutable dereference into a function that cannot normally be called in suffix position. Read more

Pipes a reference into a function that cannot ordinarily be called in suffix position. Read more

Pipes a mutable reference into a function that cannot ordinarily be called in suffix position. Read more

Should always be Self

Immutable access to a value. Read more

Mutable access to a value. Read more

Immutable access to the Borrow<B> of a value. Read more

Mutable access to the BorrowMut<B> of a value. Read more

Immutable access to the AsRef<R> view of a value. Read more

Mutable access to the AsMut<R> view of a value. Read more

Immutable access to the Deref::Target of a value. Read more

Mutable access to the Deref::Target of a value. Read more

Calls .tap() only in debug builds, and is erased in release builds.

Calls .tap_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_borrow() only in debug builds, and is erased in release builds. Read more

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_ref() only in debug builds, and is erased in release builds. Read more

Calls .tap_ref_mut() only in debug builds, and is erased in release builds. Read more

Calls .tap_deref() only in debug builds, and is erased in release builds. Read more

Calls .tap_deref_mut() only in debug builds, and is erased in release builds. Read more

Provides immutable access for inspection. Read more

Calls tap in debug builds, and does nothing in release builds.

Provides mutable access for modification. Read more

Calls tap_mut in debug builds, and does nothing in release builds.

Provides immutable access to the reference for inspection.

Calls tap_ref in debug builds, and does nothing in release builds.

Provides mutable access to the reference for modification.

Calls tap_ref_mut in debug builds, and does nothing in release builds.

Provides immutable access to the borrow for inspection. Read more

Calls tap_borrow in debug builds, and does nothing in release builds.

Provides mutable access to the borrow for modification.

Calls tap_borrow_mut in debug builds, and does nothing in release builds. Read more

Immutably dereferences self for inspection.

Calls tap_deref in debug builds, and does nothing in release builds.

Mutably dereferences self for modification.

Calls tap_deref_mut in debug builds, and does nothing in release builds. Read more

The resulting type after obtaining ownership.

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

🔬 This is a nightly-only experimental API. (toowned_clone_into)

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

Attempts to convert self into T using TryInto<T>. Read more

Attempts to convert self into a target type. Read more

The type returned in the event of a conversion error.

Performs the conversion.

The type returned in the event of a conversion error.

Performs the conversion.

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

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