[][src]Struct roa_core::Context

pub struct Context<S> { /* fields omitted */ }

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

Type of the first parameter in a middleware.

Example

use roa_core::App;
use log::info;
use async_std::fs::File;

#[async_std::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let server = App::new(())
        .gate_fn(|ctx, next| async move {
            info!("{} {}", ctx.method().await, ctx.uri().await);
            next().await
        })
        .end(|ctx| async move {
            ctx.resp_mut().await.write(File::open("assets/welcome.html").await?);
            Ok(())
        })
        .listen("127.0.0.1:8000", |addr| {
            info!("Server is listening on {}", addr)
        })?;
    // server.await;
    Ok(())
}

Methods

impl<S> Context<S>[src]

pub async fn req<'_, '_>(&'_ self) -> RwLockReadGuard<'_, Request>[src]

Get an immutable reference of request.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            assert_eq!(Method::GET, ctx.req().await.method);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn resp<'_, '_>(&'_ self) -> RwLockReadGuard<'_, Response>[src]

Get an immutable reference of response.

Example

use roa_core::App;
use async_std::task::spawn;
use http::StatusCode;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            assert_eq!(StatusCode::OK, ctx.resp().await.status);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn state<'_, '_>(&'_ self) -> RwLockReadGuard<'_, S>[src]

Get an immutable reference of state.

Example

use roa_core::{App, Model};
use log::info;
use async_std::task::spawn;
use http::StatusCode;

struct AppModel {
    default_id: u64,
}

struct AppState {
    id: u64,
}

impl AppModel {
    fn new() -> Self {
        Self {
            default_id: 0,
        }
    }
}

impl Model for AppModel {
    type State = AppState;
    fn new_state(&self) -> Self::State {
        AppState {
            id: self.default_id,
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(AppModel::new())
        .gate_fn(|ctx, next| async move {
            ctx.state_mut().await.id = 1;
            next().await
        })
        .end(|ctx| async move {
            let id = ctx.state().await.id;
            assert_eq!(1, id);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn req_mut<'_, '_>(&'_ self) -> RwLockWriteGuard<'_, Request>[src]

Get a mutable reference of request.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .gate_fn(|ctx, next| async move {
            ctx.req_mut().await.method = Method::POST;
            next().await
        })
        .end(|ctx| async move {
            assert_eq!(Method::POST, ctx.req().await.method);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn resp_mut<'_, '_>(&'_ self) -> RwLockWriteGuard<'_, Response>[src]

Get a mutable reference of response.

Example

use roa_core::App;
use async_std::task::spawn;
use http::StatusCode;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            ctx.resp_mut().await.write_buf(b"Hello, World!".as_ref());
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    assert_eq!("Hello, World!", resp.text().await?);
    Ok(())
}

pub async fn state_mut<'_, '_>(&'_ self) -> RwLockWriteGuard<'_, S>[src]

Get a mutable reference of state.

Example

use roa_core::{App, Model};
use log::info;
use async_std::task::spawn;
use http::StatusCode;

struct AppModel {
    default_id: u64,
}

struct AppState {
    id: u64,
}

impl AppModel {
    fn new() -> Self {
        Self {
            default_id: 0,
        }
    }
}

impl Model for AppModel {
    type State = AppState;
    fn new_state(&self) -> Self::State {
        AppState {
            id: self.default_id,
        }
    }
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(AppModel::new())
        .gate_fn(|ctx, next| async move {
            ctx.state_mut().await.id = 1;
            next().await
        })
        .end(|ctx| async move {
            let id = ctx.state().await.id;
            assert_eq!(1, id);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn uri<'_>(&'_ self) -> Uri[src]

Clone URI.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            assert_eq!("/path", ctx.uri().await.to_string());
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/path", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn method<'_>(&'_ self) -> Method[src]

Clone request::method.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            assert_eq!(Method::GET, ctx.method().await);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/path", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn header<'_>(
    &'_ self,
    name: impl AsHeaderName
) -> Option<Result<String, ToStrError>>
[src]

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

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method, header};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            assert_eq!(
                "text/plain",
                ctx.header(&header::CONTENT_TYPE).await.unwrap().unwrap()
            );
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::Client::new()
        .get(&format!("http://{}", addr))
        .header(&header::CONTENT_TYPE, "text/plain")
        .send()
        .await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn header_value<'_>(
    &'_ self,
    name: impl AsHeaderName
) -> Option<HeaderValue>
[src]

Search for a header value and clone it.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method, header};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            assert_eq!(
                "text/plain",
                ctx.header_value(&header::CONTENT_TYPE).await.unwrap().to_str().unwrap()
            );
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::Client::new()
        .get(&format!("http://{}", addr))
        .header(&header::CONTENT_TYPE, "text/plain")
        .send()
        .await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn status<'_>(&'_ self) -> StatusCode[src]

Clone response::status.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            assert_eq!(StatusCode::OK, ctx.status().await);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/path", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn version<'_>(&'_ self) -> Version[src]

Clone request::version.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Version};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .end(|ctx| async move {
            assert_eq!(Version::HTTP_11, ctx.version().await);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/path", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn store<'a, '_, T: 'static>(
    &'_ self,
    name: &'a str,
    value: String
) -> Option<Variable<'a>>
[src]

Store key-value pair. Each type has its namespace.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method};

struct Symbol;
struct AnotherSymbol;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .gate_fn(|ctx, next| async move {
            ctx.store::<Symbol>("id", "1".to_owned()).await;
            next().await
        })
        .end(|ctx| async move {
            assert_eq!(1, ctx.load::<Symbol>("id").await.unwrap().parse::<i32>()?);
            assert!(ctx.load::<AnotherSymbol>("id").await.is_none());
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/path", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

pub async fn load<'a, '_, T: 'static>(
    &'_ self,
    name: &'a str
) -> Option<Variable<'a>>
[src]

Search for value by key.

Example

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method};

struct Symbol;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .gate_fn(|ctx, next| async move {
            ctx.store::<Symbol>("id", "1".to_owned()).await;
            next().await
        })
        .end(|ctx| async move {
            assert_eq!(1, ctx.load::<Symbol>("id").await.unwrap().parse::<i32>()?);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/path", addr)).await?;
    assert_eq!(StatusCode::OK, resp.status());
    Ok(())
}

Parse fails

The loaded value can be parsed as str, and return a 400 BAD REQUEST Error if fails.

use roa_core::App;
use async_std::task::spawn;
use http::{StatusCode, Method};

struct Symbol;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let (addr, server) = App::new(())
        .gate_fn(|ctx, next| async move {
            ctx.store::<Symbol>("id", "x".to_owned()).await;
            next().await
        })
        .end(|ctx| async move {
            assert_eq!(1, ctx.load::<Symbol>("id").await.unwrap().parse::<i32>()?);
            Ok(())
        })
        .run_local()?;
    spawn(server);
    let resp = reqwest::get(&format!("http://{}/path", addr)).await?;
    assert_eq!(StatusCode::BAD_REQUEST, resp.status());
    Ok(())
}

pub fn remote_addr(&self) -> SocketAddr[src]

Get remote socket addr.

pub fn raw_stream(&self) -> &TcpStream[src]

Get reference of raw async_std::net::TcpStream. This method is dangerous, it's reserved for special scene like websocket.

Trait Implementations

impl<S> Clone for Context<S>[src]

Auto Trait Implementations

impl<S> !RefUnwindSafe for Context<S>

impl<S> Send for Context<S> where
    S: Send + Sync

impl<S> Sync for Context<S> where
    S: Send + Sync

impl<S> Unpin for Context<S>

impl<S> !UnwindSafe for Context<S>

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T> ToOwned for T where
    T: Clone
[src]

type Owned = T

The resulting type after obtaining ownership.

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

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

The type returned in the event of a conversion error.