[][src]Trait actix_web::FromRequest

pub trait FromRequest<P>: Sized {
    type Error: Into<Error>;
    type Future: IntoFuture<Item = Self, Error = Self::Error>;
    fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future;
}

Trait implemented by types that can be extracted from request.

Types that implement this trait can be used with Route handlers.

Associated Types

type Error: Into<Error>

The associated error which can be returned.

type Future: IntoFuture<Item = Self, Error = Self::Error>

Future that resolves to a Self

Loading content...

Required methods

fn from_request(req: &mut ServiceFromRequest<P>) -> Self::Future

Convert request to a Self

Loading content...

Implementations on Foreign Types

impl<T: 'static, P> FromRequest<P> for Option<T> where
    T: FromRequest<P>,
    T::Future: 'static, 
[src]

Optionally extract a field from the request

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

Example

use actix_web::{web, dev, App, Error, FromRequest};
use actix_web::error::ErrorBadRequest;
use rand;

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

impl<P> FromRequest<P> for Thing {
    type Error = Error;
    type Future = Result<Self, Self::Error>;

    fn from_request(req: &mut dev::ServiceFromRequest<P>) -> Self::Future {
        if rand::random() {
            Ok(Thing { name: "thingy".into() })
        } else {
            Err(ErrorBadRequest("no luck"))
        }

    }
}

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

fn main() {
    let app = App::new().service(
        web::resource("/users/:first").route(
            web::post().to(index))
    );
}

type Error = Error

type Future = Box<dyn Future<Item = Option<T>, Error = Error>>

impl<T: 'static, P> FromRequest<P> for Result<T, T::Error> where
    T: FromRequest<P>,
    T::Future: 'static,
    T::Error: 'static, 
[src]

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

use actix_web::{web, dev, App, Result, Error, FromRequest};
use actix_web::error::ErrorBadRequest;
use rand;

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

impl<P> FromRequest<P> for Thing {
    type Error = Error;
    type Future = Result<Thing, Error>;

    fn from_request(req: &mut dev::ServiceFromRequest<P>) -> Self::Future {
        if rand::random() {
            Ok(Thing { name: "thingy".into() })
        } else {
            Err(ErrorBadRequest("no luck"))
        }
    }
}

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

fn main() {
    let app = App::new().service(
        web::resource("/users/:first").route(web::post().to(index))
    );
}

type Error = Error

type Future = Box<dyn Future<Item = Result<T, T::Error>, Error = Error>>

impl<P> FromRequest<P> for String where
    P: Stream<Item = Bytes, Error = PayloadError> + 'static, 
[src]

Extract text information from a request's body.

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

PayloadConfig allows to configure extraction process.

Example

use actix_web::{web, App};

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

fn main() {
    let app = App::new().service(
        web::resource("/index.html").route(
            web::get()
               .data(web::PayloadConfig::new(4096)) // <- limit size of the payload
               .to(index))  // <- register handler with extractor params
    );
}

type Error = Error

type Future = Either<Box<dyn Future<Item = String, Error = Error>>, FutureResult<String, Error>>

Loading content...

Implementors

impl<P> FromRequest<P> for Identity[src]

Extractor implementation for Identity type.

use actix_web::middleware::identity::Identity;

fn index(id: Identity) -> String {
    // access request identity
    if let Some(id) = id.identity() {
        format!("Welcome! {}", id)
    } else {
        "Welcome Anonymous!".to_owned()
    }
}

impl<P> FromRequest<P> for HttpRequest[src]

It is possible to get HttpRequest as an extractor handler parameter

Example

use actix_web::{web, App, HttpRequest};

/// extract `Thing` from request
fn index(req: HttpRequest) -> String {
   format!("Got thing: {:?}", req)
}

fn main() {
    let app = App::new().service(
        web::resource("/users/{first}").route(
            web::get().to(index))
    );
}

type Error = Error

type Future = Result<Self, Error>

impl<P> FromRequest<P> for Bytes where
    P: Stream<Item = Bytes, Error = PayloadError> + 'static, 
[src]

Request binary data from a request's payload.

Loads request's payload and construct Bytes instance.

PayloadConfig allows to configure extraction process.

Example

use bytes::Bytes;
use actix_web::{web, App};

/// extract binary data from request
fn index(body: Bytes) -> String {
    format!("Body {:?}!", body)
}

fn main() {
    let app = App::new().service(
        web::resource("/index.html").route(
            web::get().to(index))
    );
}

type Error = Error

type Future = Either<Box<dyn Future<Item = Bytes, Error = Error>>, FutureResult<Bytes, Error>>

impl<P> FromRequest<P> for Multipart where
    P: Stream<Item = Bytes, Error = PayloadError> + 'static, 
[src]

Get request's payload as multipart stream

Content-type: multipart/form-data;

Server example

use actix_web::{web, HttpResponse, Error};

fn index(payload: web::Multipart) -> impl Future<Item = HttpResponse, Error = Error> {
    payload.from_err()               // <- get multipart stream for current request
       .and_then(|item| match item { // <- iterate over multipart items
           web::MultipartItem::Field(field) => {
               // Field in turn is stream of *Bytes* object
               Either::A(field.from_err()
                         .fold((), |_, chunk| {
                             println!("-- CHUNK: \n{:?}", std::str::from_utf8(&chunk));
                             Ok::<_, Error>(())
                         }))
            },
            web::MultipartItem::Nested(mp) => {
                // Or item could be nested Multipart stream
                Either::B(ok(()))
            }
        })
        .fold((), |_, _| Ok::<_, Error>(()))
        .map(|_| HttpResponse::Ok().into())
}

impl<P> FromRequest<P> for Payload where
    P: Stream<Item = Bytes, Error = PayloadError> + 'static, 
[src]

Get request's payload stream

Example

use futures::{Future, Stream};
use actix_web::{web, error, App, Error, HttpResponse};

/// extract binary data from request
fn index(body: web::Payload) -> impl Future<Item = HttpResponse, Error = Error>
{
    body.map_err(Error::from)
        .fold(web::BytesMut::new(), move |mut body, chunk| {
            body.extend_from_slice(&chunk);
            Ok::<_, Error>(body)
         })
         .and_then(|body| {
             format!("Body {:?}!", body);
             Ok(HttpResponse::Ok().finish())
         })
}

fn main() {
    let app = App::new().service(
        web::resource("/index.html").route(
            web::get().to_async(index))
    );
}

impl<T, P> FromRequest<P> for Form<T> where
    T: DeserializeOwned + 'static,
    P: Stream<Item = Bytes, Error = PayloadError> + 'static, 
[src]

type Error = Error

type Future = Box<dyn Future<Item = Self, Error = Error>>

impl<T, P> FromRequest<P> for Json<T> where
    T: DeserializeOwned + 'static,
    P: Stream<Item = Bytes, Error = PayloadError> + 'static, 
[src]

Json extractor. Allow to extract typed information from request's payload.

To extract typed information from request's body, the type T must implement the Deserialize trait from serde.

JsonConfig allows to configure extraction process.

Example

#[macro_use] extern crate serde_derive;
use actix_web::{web, App};

#[derive(Deserialize)]
struct Info {
    username: String,
}

/// deserialize `Info` from request's body
fn index(info: web::Json<Info>) -> String {
    format!("Welcome {}!", info.username)
}

fn main() {
    let app = App::new().service(
        web::resource("/index.html").route(
           web::post().to(index))
    );
}

type Error = Error

type Future = Box<dyn Future<Item = Self, Error = Error>>

impl<T, P> FromRequest<P> for Path<T> where
    T: DeserializeOwned
[src]

Extract typed information from the request's path.

Example

use actix_web::{web, App};

/// extract path info from "/{username}/{count}/index.html" url
/// {username} - deserializes to a String
/// {count} -  - deserializes to a u32
fn index(info: web::Path<(String, u32)>) -> String {
    format!("Welcome {}! {}", info.0, info.1)
}

fn main() {
    let app = App::new().service(
        web::resource("/{username}/{count}/index.html") // <- define path parameters
             .route(web::get().to(index)) // <- register handler with `Path` extractor
    );
}

It is possible to extract path information to a specific type that implements Deserialize trait from serde.

#[macro_use] extern crate serde_derive;
use actix_web::{web, App, Error};

#[derive(Deserialize)]
struct Info {
    username: String,
}

/// extract `Info` from a path using serde
fn index(info: web::Path<Info>) -> Result<String, Error> {
    Ok(format!("Welcome {}!", info.username))
}

fn main() {
    let app = App::new().service(
        web::resource("/{username}/index.html") // <- define path parameters
             .route(web::get().to(index)) // <- use handler with Path` extractor
    );
}

type Error = Error

type Future = Result<Self, Error>

impl<T, P> FromRequest<P> for Query<T> where
    T: DeserializeOwned
[src]

Extract typed information from from the request's query.

Example

#[macro_use] extern crate serde_derive;
use actix_web::{web, App};

#[derive(Debug, Deserialize)]
pub enum ResponseType {
   Token,
   Code
}

#[derive(Deserialize)]
pub struct AuthRequest {
   id: u64,
   response_type: ResponseType,
}

// Use `Query` extractor for query information.
// This handler get called only if request's query contains `username` field
// The correct request for this handler would be `/index.html?id=64&response_type=Code"`
fn index(info: web::Query<AuthRequest>) -> String {
    format!("Authorization request for client with id={} and type={:?}!", info.id, info.response_type)
}

fn main() {
    let app = App::new().service(
       web::resource("/index.html")
           .route(web::get().to(index))); // <- use `Query` extractor
}

type Error = Error

type Future = Result<Self, Error>

impl<T: 'static, P> FromRequest<P> for Data<T>[src]

type Error = Error

type Future = Result<Self, Error>

impl<T: 'static, P> FromRequest<P> for RouteData<T>[src]

type Error = Error

type Future = Result<Self, Error>

Loading content...