pub trait RequestPayloadExt {
    // Required method
    fn payload<D>(&self) -> Result<Option<D>, PayloadError>
       where D: DeserializeOwned;
}
Expand description

Extensions for lambda_http::Request structs.

Examples

A request’s body can be deserialized if its correctly encoded as per the request’s Content-Type header. The two supported content types are application/x-www-form-urlencoded and application/json.

The following handler will work an http request body of x=1&y=2 as well as {"x":1, "y":2} respectively.

use lambda_http::{
    service_fn, Body, Context, Error, IntoResponse, Request, RequestPayloadExt, Response,
};
use serde::Deserialize;

#[derive(Debug, Default, Deserialize)]
struct Args {
  #[serde(default)]
  x: usize,
  #[serde(default)]
  y: usize
}

#[tokio::main]
async fn main() -> Result<(), Error> {
  lambda_http::run(service_fn(add)).await?;
  Ok(())
}

async fn add(
  request: Request
) -> Result<Response<Body>, Error> {
  let args: Args = request.payload()
    .unwrap_or_else(|_parse_err| None)
    .unwrap_or_default();
  Ok(
     Response::new(
       format!(
         "{} + {} = {}",
         args.x,
         args.y,
         args.x + args.y
       ).into()
     )
  )
}

Required Methods§

source

fn payload<D>(&self) -> Result<Option<D>, PayloadError>where D: DeserializeOwned,

Return the result of a payload parsed into a type that implements serde::Deserialize

Currently only application/x-www-form-urlencoded and application/json flavors of content type are supported

A PayloadError will be returned for undeserializable payloads. If no body is provided, Ok(None) will be returned.

Implementations on Foreign Types§

source§

impl RequestPayloadExt for Request<Body>

source§

fn payload<D>(&self) -> Result<Option<D>, PayloadError>where for<'de> D: Deserialize<'de>,

Implementors§