Skip to main content

Request

Struct Request 

Source
pub struct Request<'a> { /* private fields */ }
Expand description

A borrowed view of one HTTP request, with a body limit.

§Examples

use davidrs::http::Request;
use serde::Deserialize;

#[derive(Deserialize)]
struct Page {
    page: u32,
}

let native = lambda_http::http::Request::builder()
    .uri("https://example.com/orders?page=2")
    .body(lambda_http::Body::Empty)
    .unwrap();
let page: Page = Request::new(&native).query().unwrap();
assert_eq!(page.page, 2);

Implementations§

Source§

impl<'a> Request<'a>

Source

pub fn new(inner: &'a Request) -> Self

Wraps a native request with DEFAULT_BODY_LIMIT.

Source

pub fn with_body_limit(self, limit: usize) -> Self

Sets the body limit every bounded read checks.

Source

pub fn native(&self) -> &'a Request

The native request, for anything this view does not expose.

Source

pub fn method(&self) -> &'a Method

The request method.

Source

pub fn headers(&self) -> &'a HeaderMap

All request headers.

Source

pub fn header(&self, name: &str) -> Option<&'a str>

One header as text, if present and valid UTF-8.

Source

pub fn raw_body(&self) -> &'a [u8] ⓘ

The exact body bytes, for signatures and hashing; empty when there is no body.

This read is not bounded: the pipeline has already checked the body limit before any decoder runs.

Source

pub fn query_string(&self) -> &'a str

The raw query string, without the leading ?.

Source

pub fn query_pairs(&self) -> Vec<(String, String)>

The query parameters the gateway parsed, as (name, value) pairs with repetitions kept.

Use it for lists that arrive as ?tag=a&tag=b.

Source

pub fn path_parameters(&self) -> HashMap<String, String>

The path parameters the gateway matched, by name.

Source

pub fn path<T: DeserializeOwned>(&self) -> Result<T, Failure>

Deserializes the path parameters into T.

§Errors

Returns a 400 (codes::INVALID_PATH) when a parameter is missing or has the wrong shape.

Source

pub fn query<T: DeserializeOwned>(&self) -> Result<T, Failure>

Deserializes the query string into T.

§Errors

Returns a 400 (codes::INVALID_QUERY) when a parameter is missing or has the wrong shape.

Source

pub fn source_ip(&self) -> String

The caller’s IP address as the gateway saw it, or "unknown".

Reads sourceIp from an HTTP API or, with the apigw-rest feature, a REST API request context. A request with no context, an empty address or another gateway flavour gives "unknown". Forwarded headers are otherwise ignored on purpose: trusting them needs a proxy policy of the application’s own, and without one any caller could choose its own rate-limit key.

With the alb feature, an Application Load Balancer request, whose context has no address, gives the last address of X-Forwarded-For: the one the load balancer appends in its default append mode. With multi-value headers the header can arrive as several values, one per line the client sent, and the address is the last one of the last value, never an earlier line a client could choose. With the preserve or remove modes that address is not the caller’s, so keep append wherever this address is a rate-limit key.

Source

pub fn json<T: DeserializeOwned>(&self) -> Result<T, Failure>

Deserializes a JSON body, bounded by the body limit.

§Errors

Returns a 413 when the body exceeds the limit, a 415 when it declares a media type other than JSON, and a 400 when it is empty or malformed.

Source

pub fn json_bounded<T: DeserializeOwned>( &self, limit: usize, ) -> Result<T, Failure>

Deserializes a JSON body under a tighter byte limit.

The effective limit is the smaller of limit and the request’s own, and it is checked before parsing, so an oversized payload never reaches serde_json.

§Errors

Returns a 413 when the body exceeds the limit, a 415 when it declares a media type other than JSON, and a 400 when it is empty or malformed.

Source

pub fn form<T: DeserializeOwned>(&self) -> Result<T, Failure>

Deserializes an application/x-www-form-urlencoded body, bounded by the body limit: what an HTML form, a webhook or an OAuth client posts.

Names and values are percent-decoded, and + reads as a space. A missing Content-Type is accepted, as for JSON. Each field is read once; for a name that repeats, parse Request::raw_body yourself.

§Errors

Returns a 413 when the body exceeds the limit, a 415 when it declares another media type, and a 400 when it does not deserialize into T.

§Examples
use davidrs::http::{Body, Request};

#[derive(serde::Deserialize)]
struct Signup {
    email: String,
    plan: Option<String>,
}

let native = lambda_http::http::Request::builder()
    .method("POST")
    .header("content-type", "application/x-www-form-urlencoded")
    .body(Body::Text("email=ada%40example.com&plan=team+plus".to_owned()))
    .unwrap();
let signup: Signup = Request::new(&native).form().unwrap();
assert_eq!(signup.email, "ada@example.com");
assert_eq!(signup.plan.as_deref(), Some("team plus"));
Source

pub fn check_body_limit(&self) -> Result<(), Failure>

Checks the body against the limit without reading it.

The pipeline calls this before any decoder, so a decoder that reads Request::raw_body is bounded too.

§Errors

Returns a 413 (codes::BODY_TOO_LARGE) when the body is larger than the limit; the limit is in the failure’s detail.

Source

pub fn json_text(&self) -> Result<&'a str, Failure>

The body as strict UTF-8 text, for an application’s own JSON decoder.

Size and media type are checked as in Request::json; the caller still validates the JSON syntax and the input contract.

§Errors

Returns a 413 when the body exceeds the limit, a 415 when it declares a media type other than JSON, and a 400 when it is not UTF-8.

Source

pub fn media_type(&self) -> Option<Cow<'a, str>>

The Content-Type, lowercased and without parameters.

Source§

impl Request<'_>

Source

pub fn validated_json<T>(&self) -> Result<T, Failure>
where T: DeserializeOwned + Validate<Context = ()>,

Deserializes a JSON body and validates it with Garde.

Validates the decoded value only. For rules that need a context, decode with Request::json and call validate_with in the handler.

§Errors

Returns the failures of Request::json, or a 400 (codes::INVALID_BODY) when a constraint fails.

Trait Implementations§

Source§

impl<'a> Clone for Request<'a>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<'a> Copy for Request<'a>

Source§

impl<'a> Debug for Request<'a>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<'a> !RefUnwindSafe for Request<'a>

§

impl<'a> !UnwindSafe for Request<'a>

§

impl<'a> Freeze for Request<'a>

§

impl<'a> Send for Request<'a>

§

impl<'a> Sync for Request<'a>

§

impl<'a> Unpin for Request<'a>

§

impl<'a> UnsafeUnpin for Request<'a>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> AsOut<T> for T
where T: Copy,

Source§

fn as_out(&mut self) -> Out<'_, T>

Returns an out reference to self.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self> ⓘ

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<Unshared, Shared> IntoShared<Shared> for Unshared
where Shared: FromUnshared<Unshared>,

Source§

fn into_shared(self) -> Shared

Creates a shared type from an unshared type.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Requirement<T> for T

Source§

const REQUIRED: bool = const REQUIRED: bool = true;

Whether a request without the value is refused.
Source§

fn fulfill(found: Option<T>) -> Option<T>

Converts what was found, or None when a required value is missing.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more