# actix_web::HttpMessage - Rust
API documentation for the Rust `HttpMessage` trait in crate `actix_web`.
Keywords: rust, rustlang, rust-lang, HttpMessage

# [−] [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 Stream: Stream<Item = Bytes, Error = PayloadError> + Sized`

Type of message payload stream

## Required Methods

### `fn headers(&self) -> &HeaderMap`

Read the message headers.

### `fn payload(&self) -> Self::Stream`

Message payload stream

## Provided Methods

### `fn content_type(&self) -> &str`

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

### `fn encoding(&self) -> Result<EncodingRef, ContentTypeError>`

Get content type encoding

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

### `fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError>`

Convert the request content type to a known mime type.

### `fn chunked(&self) -> Result<bool, ParseError>`

Check if request has chunked transfer encoding

### `fn body(&self) -> MessageBody<Self>`

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()
    }

### `fn urlencoded<T: DeserializeOwned>(&self) -> UrlEncoded<Self, T>`

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())
              }),
        )
    }

### `fn json<T: DeserializeOwned>(&self) -> JsonBody<Self, T>`

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()
    }

### `fn multipart(&self) -> Multipart<Self::Stream>`

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()
    }

### `fn readlines(&self) -> Readlines<Self>`

Return stream of lines.

## Implementors

###

`impl HttpMessage for ClientResponse`

[src]

#### `type Stream = Box<Pipeline>`

####

`fn headers(&self) -> &HeaderMap`

[src]

Get the headers from the response.

####

`fn payload(&self) -> Box<Pipeline>`

[src]

####

`fn content_type(&self) -> &str`

[src]

####

`fn encoding(&self) -> Result<EncodingRef, ContentTypeError>`

[src]

####

`fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError>`

[src]

####

`fn chunked(&self) -> Result<bool, ParseError>`

[src]

####

`fn body(&self) -> MessageBody<Self>`

[src]

####

`fn urlencoded<T: DeserializeOwned>(&self) -> UrlEncoded<Self, T>`

[src]

####

`fn json<T: DeserializeOwned>(&self) -> JsonBody<Self, T>`

[src]

####

`fn multipart(&self) -> Multipart<Self::Stream>`

[src]

####

`fn readlines(&self) -> Readlines<Self>`

[src]

###

`impl HttpMessage for Request`

[src]

#### `type Stream = Payload`

####

`fn headers(&self) -> &HeaderMap`

[src]

####

`fn payload(&self) -> Payload`

[src]

####

`fn content_type(&self) -> &str`

[src]

####

`fn encoding(&self) -> Result<EncodingRef, ContentTypeError>`

[src]

####

`fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError>`

[src]

####

`fn chunked(&self) -> Result<bool, ParseError>`

[src]

####

`fn body(&self) -> MessageBody<Self>`

[src]

####

`fn urlencoded<T: DeserializeOwned>(&self) -> UrlEncoded<Self, T>`

[src]

####

`fn json<T: DeserializeOwned>(&self) -> JsonBody<Self, T>`

[src]

####

`fn multipart(&self) -> Multipart<Self::Stream>`

[src]

####

`fn readlines(&self) -> Readlines<Self>`

[src]

###

`impl<S> HttpMessage for HttpRequest<S>`

[src]

#### `type Stream = Payload`

####

`fn headers(&self) -> &HeaderMap`

[src]

####

`fn payload(&self) -> Payload`

[src]

####

`fn content_type(&self) -> &str`

[src]

####

`fn encoding(&self) -> Result<EncodingRef, ContentTypeError>`

[src]

####

`fn mime_type(&self) -> Result<Option<Mime>, ContentTypeError>`

[src]

####

`fn chunked(&self) -> Result<bool, ParseError>`

[src]

####

`fn body(&self) -> MessageBody<Self>`

[src]

####

`fn urlencoded<T: DeserializeOwned>(&self) -> UrlEncoded<Self, T>`

[src]

####

`fn json<T: DeserializeOwned>(&self) -> JsonBody<Self, T>`

[src]

####

`fn multipart(&self) -> Multipart<Self::Stream>`

[src]

####

`fn readlines(&self) -> Readlines<Self>`

[src]

# Help

## Keyboard Shortcuts

`?`
  Show this help dialog
`S`
  Focus the search field
`↑`
  Move up in search results
`↓`
  Move down in search results
`↹`
  Switch tab
`⏎`
  Go to active search result
`+`
  Expand all sections
`-`
  Collapse all sections

## Search Tricks

Prefix searches with a type followed by a colon (e.g. `fn:`) to restrict the search to a given type.

Accepted types are: `fn`, `mod`, `struct`, `enum`, `trait`, `type`, `macro`, and `const`.

Search functions by type signature (e.g. `vec -> usize` or `* -> vec`)

Search multiple things at once by splitting your query with comma (e.g. `str,u8` or `String,struct:Vec,test`)