pub trait FromRequest<S>: Sized {
    type Config: Default;
    type Result: Into<AsyncResult<Self>>;

    fn from_request(req: &HttpRequest<S>, cfg: &Self::Config) -> Self::Result;

    fn extract(req: &HttpRequest<S>) -> Self::Result { ... }
}
Expand description

Trait implemented by types that can be extracted from request.

Types that implement this trait can be used with Route::with() method.

Required Associated Types

Configuration for conversion process

Future that resolves to a Self

Required Methods

Convert request to a Self

Provided Methods

Convert request to a Self

This method uses default extractor configuration

Implementations on Foreign Types

Request payload extractor.

Loads request’s payload and construct Bytes instance.

PayloadConfig allows to configure extraction process.

Example
extern crate bytes;
use actix_web::{http, App, Result};

/// extract text data from request
fn index(body: bytes::Bytes) -> Result<String> {
    Ok(format!("Body {:?}!", body))
}

fn main() {
    let app = App::new()
        .resource("/index.html", |r| r.method(http::Method::GET).with(index));
}

Extract text information from the request’s body.

Text extractor automatically decode body according to the request’s charset.

PayloadConfig allows to configure extraction process.

Example
use actix_web::{http, App, Result};

/// extract text data from request
fn index(body: String) -> Result<String> {
    Ok(format!("Body {}!", body))
}

fn main() {
    let app = App::new().resource("/index.html", |r| {
        r.method(http::Method::GET)
               .with_config(index, |cfg| { // <- register handler with extractor params
                  cfg.0.limit(4096);  // <- limit size of the payload
                })
    });
}

Optionally extract a field from the request

If the FromRequest for T fails, return None rather than returning an error response

Example
extern crate rand;
#[macro_use] extern crate serde_derive;
use actix_web::{http, App, Result, HttpRequest, Error, FromRequest};
use actix_web::error::ErrorBadRequest;

#[derive(Debug, Deserialize)]
struct Thing { name: String }

impl<S> FromRequest<S> for Thing {
    type Config = ();
    type Result = Result<Thing, Error>;

    #[inline]
    fn from_request(req: &HttpRequest<S>, _cfg: &Self::Config) -> Self::Result {
        if rand::random() {
            Ok(Thing { name: "thingy".into() })
        } else {
            Err(ErrorBadRequest("no luck"))
        }

    }
}

/// extract text data from request
fn index(supplied_thing: Option<Thing>) -> Result<String> {
    match supplied_thing {
        // Puns not intended
        Some(thing) => Ok(format!("Got something: {:?}", thing)),
        None => Ok(format!("No thing!"))
    }
}

fn main() {
    let app = App::new().resource("/users/:first", |r| {
        r.method(http::Method::POST).with(index)
    });
}

Optionally extract a field from the request or extract the Error if unsuccessful

If the FromRequest for T fails, inject Err into handler rather than returning an error response

Example
extern crate rand;
#[macro_use] extern crate serde_derive;
use actix_web::{http, App, Result, HttpRequest, Error, FromRequest};
use actix_web::error::ErrorBadRequest;

#[derive(Debug, Deserialize)]
struct Thing { name: String }

impl<S> FromRequest<S> for Thing {
    type Config = ();
    type Result = Result<Thing, Error>;

    #[inline]
    fn from_request(req: &HttpRequest<S>, _cfg: &Self::Config) -> Self::Result {
        if rand::random() {
            Ok(Thing { name: "thingy".into() })
        } else {
            Err(ErrorBadRequest("no luck"))
        }

    }
}

/// extract text data from request
fn index(supplied_thing: Result<Thing>) -> Result<String> {
    match supplied_thing {
        Ok(thing) => Ok(format!("Got thing: {:?}", thing)),
        Err(e) => Ok(format!("Error extracting thing: {}", e))
    }
}

fn main() {
    let app = App::new().resource("/users/:first", |r| {
        r.method(http::Method::POST).with(index)
    });
}

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

FromRequest implementation for tuple

Implementors

Extractor implementation for Session type.

use actix_web::middleware::session::Session;

fn index(session: Session) -> Result<&'static str> {
    // access session data
    if let Some(count) = session.get::<i32>("counter")? {
        session.set("counter", count + 1)?;
    } else {
        session.set("counter", 1)?;
    }

    Ok("Welcome!")
}