[][src]Trait actix_web::HttpMessage

pub trait HttpMessage: Sized {
    type Stream: Stream<Item = Bytes, Error = PayloadError> + Sized;
    fn headers(&self) -> &HeaderMap;
fn payload(&self) -> Self::Stream; fn content_type(&self) -> &str { ... }
fn encoding(&self) -> Result<EncodingRef, ContentTypeError> { ... }
fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError> { ... }
fn chunked(&self) -> Result<bool, ParseError> { ... }
fn body(&self) -> MessageBody<Self> { ... }
fn urlencoded<T: DeserializeOwned>(&self) -> UrlEncoded<Self, T> { ... }
fn json<T: DeserializeOwned>(&self) -> JsonBody<Self, T> { ... }
fn multipart(&self) -> Multipart<Self::Stream> { ... }
fn readlines(&self) -> Readlines<Self> { ... } }

Trait that implements general purpose operations on http messages

Associated Types

Type of message payload stream

Required Methods

Read the message headers.

Message payload stream

Provided Methods

Read the request content type. If request does not contain Content-Type header, empty str get returned.

Get content type encoding

UTF-8 is used by default, If request charset is not set.

Convert the request content type to a known mime type.

Check if request has chunked transfer encoding

Load http message body.

By default only 256Kb payload reads to a memory, then PayloadError::Overflow get returned. Use MessageBody::limit() method to change upper limit.

Server example

use actix_web::{
    AsyncResponder, FutureResponse, HttpMessage, HttpRequest, HttpResponse,
};
use bytes::Bytes;
use futures::future::Future;

fn index(mut req: HttpRequest) -> FutureResponse<HttpResponse> {
    req.body()                     // <- get Body future
       .limit(1024)                // <- change max size of the body to a 1kb
       .from_err()
       .and_then(|bytes: Bytes| {  // <- complete body
           println!("==== BODY ==== {:?}", bytes);
           Ok(HttpResponse::Ok().into())
       }).responder()
}

Parse application/x-www-form-urlencoded encoded request's body. Return UrlEncoded future. Form can be deserialized to any type that implements Deserialize trait from serde.

Returns error:

  • content type is not application/x-www-form-urlencoded
  • content-length is greater than 256k

Server example

use actix_web::{FutureResponse, HttpMessage, HttpRequest, HttpResponse};

fn index(mut req: HttpRequest) -> FutureResponse<HttpResponse> {
    Box::new(
        req.urlencoded::<HashMap<String, String>>()  // <- get UrlEncoded future
           .from_err()
           .and_then(|params| {  // <- url encoded parameters
               println!("==== BODY ==== {:?}", params);
               Ok(HttpResponse::Ok().into())
          }),
    )
}

Parse application/json encoded body. Return JsonBody<T> future. It resolves to a T value.

Returns error:

  • content type is not application/json
  • content length is greater than 256k

Server example

use actix_web::*;
use futures::future::{ok, Future};

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

fn index(mut req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
    req.json()                   // <- get JsonBody future
       .from_err()
       .and_then(|val: MyObj| {  // <- deserialized value
           println!("==== BODY ==== {:?}", val);
           Ok(HttpResponse::Ok().into())
       }).responder()
}

Return stream to http payload processes as multipart.

Content-type: multipart/form-data;

Server example

fn index(mut req: HttpRequest) -> Box<Future<Item = HttpResponse, Error = Error>> {
    req.multipart().from_err()       // <- get multipart stream for current request
       .and_then(|item| match item { // <- iterate over multipart items
           multipart::MultipartItem::Field(field) => {
               // Field in turn is stream of *Bytes* object
               Either::A(field.from_err()
                         .map(|c| println!("-- CHUNK: \n{:?}", str::from_utf8(&c)))
                         .finish())
            },
            multipart::MultipartItem::Nested(mp) => {
                // Or item could be nested Multipart stream
                Either::B(ok(()))
            }
        })
        .finish()  // <- Stream::finish() combinator from actix
        .map(|_| HttpResponse::Ok().into())
        .responder()
}

Return stream of lines.

Implementors

impl HttpMessage for ClientResponse
[src]

Get the headers from the response.

impl HttpMessage for Request
[src]

impl<S> HttpMessage for HttpRequest<S>
[src]