Request

Struct Request 

Source
pub struct Request { /* private fields */ }
Expand description

Contains information about a single request.

Implementations§

Source§

impl Request

Source

pub fn new( method: Span, path: Span, headers: Vec<(Span, Span)>, body: Span, buffer: Vec<u8>, ) -> Request

Create a new Request from a raw one. You probably want default() to get an empty Request.

Source

pub fn default() -> Request

Produce an empty Request.

Source

pub fn from_reader<R: Read>(reader: R) -> Result<Request>

Read a raw HTTP request from reader and create an appropriate Request to represent it.

Source

pub fn path(&self) -> &str

Path requested, starting with / and not including ?query.

Source

pub fn full_path(&self) -> &str

Full path requested, starting with / and including ?query.

Source

pub fn from_path(path: &str) -> Request

Create a request from an arbitrary path. Used in testing.

Source

pub fn set_path(&mut self, path: &str)

Give a request an arbitrary path. Can be used in tests or with filter.

Source

pub fn with_path(self, path: &str) -> Request

Give a request an arbitrary path. Can be used in tests or with filter.

Source

pub fn body(&self) -> &str

Raw body of HTTP request. If you are using methods like with_path or set_arg this will not accurately represent the raw HTTP request that was made.

Source

pub fn set_body<S: AsRef<str>>(&mut self, body: S)

Give this Request an arbitrary body from a string.

Source

pub fn with_body<S: AsRef<str>>(self, body: S) -> Request

Give this Request an arbitrary body from a string and return the new Request.

Source

pub fn method(&self) -> &str

HTTP Method

Source

pub fn set_method(&mut self, method: &str)

Give this Request a new HTTP Method.

Source

pub fn with_method(self, method: &str) -> Request

Give this Request a new HTTP Method and return the new Request.

Source

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

In a route defined with routes! like "/names/:name", calling request.arg("name") will return Some("peter") when the request is /names/peter.

Source

pub fn set_arg(&mut self, name: String, value: String)

Replace or set a new value for an arbitrary URL argument from a filter or in a test.

Source

pub fn header(&self, name: &str) -> Option<Cow<'_, str>>

Get a header value. name is case insensitive.

Source

pub fn has_form(&mut self, name: &str) -> bool

Was the given form value sent?

Source

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

Return a value from the POSTed form data.

Source

pub fn set_form(&mut self, name: &str, value: &str)

Replace or set a new value for an arbitrary URL argument from a filter or in a test.

Source

pub fn parse_form(&mut self)

Parse and decode form POST data into a Hash. Should be called when this Request is created.

Source

pub fn has_query(&self, name: &str) -> bool

Was the given query value sent?

Source

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

Return a value from the ?querystring=

Source

pub fn cache<T, F>(&self, fun: F) -> &T
where F: FnOnce(&Request) -> T, T: Send + Sync + 'static,

Request’s cache() lives for only a single Request, but can nonethenevertheless be useful to prevent looking up the same data over and over. The cache is based on the return type of the function or closure you pass to cache() using TypeCache, so make sure to create little wrapper structs if you want different functions to return the same common types, like Vec<String>:

struct PageNames(Vec<String>);
struct UserNames(Vec<String>);

Here’s an example:

use vial::prelude::*;
use page::Page;

routes! {
    GET "/" => list;
}

struct PageNames(Vec<String>);

fn all_pages(_: &Request) -> Vec<Page> {
    db::lookup("select * from pages")
}

fn page_names(req: &Request) -> PageNames {
    PageNames(req.cache(all_pages)
        .iter()
        .map(|page| page.name.clone())
        .collect::<Vec<_>>())
}

fn list_of_names(req: &Request) -> String {
    req.cache(page_names)
        .0
        .iter()
        .map(|name| format!("<li>{}</li>", name))
        .collect::<Vec<_>>()
        .join("\n")
}

fn list(req: Request) -> impl Responder {
    format!(
        "<html>
            <head><title>{title}</title></head>
            <body>
                <h1>{title}</h1>
                <h3>There are {page_count} pages:</h3>
                <ul>
                    {pages}
                </ul>
            </body>
        </html>",
        title = "List Pages",
        page_count = req.cache(all_pages).len(),
        pages = req.cache(list_of_names),
    )
}

fn main() {
    run!().unwrap();
}
Source

pub fn state<T: Send + Sync + 'static>(&self) -> &T

Access to global shared state defined with the vial::use_state! macro before starting your application with vial::run!.

use std::sync::atomic::{AtomicUsize, Ordering};
use vial::prelude::*;

routes! {
    #[filter(count)]
    GET "/" => |req|
        format!("Hits: {}", req.state::<Counter>.hits());
}

fn count(req: &mut Request) -> Option<Response> {
    req.state::<Counter>().incr();
    None
}

#[derive(Debug, Default)]
struct Counter(AtomicUsize);

impl Counter {
    fn hits(&self) -> usize {
        self.0.load(Ordering::Relaxed)
    }
    fn incr(&self) {
        self.0.fetch_add(1, Ordering::Relaxed);
    }
}

fn main() {
    use_state!(Counter::default());
    run!();
}

Trait Implementations§

Source§

impl Debug for Request

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Request

§

impl !RefUnwindSafe for Request

§

impl !Send for Request

§

impl !Sync for Request

§

impl Unpin for Request

§

impl !UnwindSafe for Request

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, 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.