paperclip_actix::web

Struct HttpRequest

pub struct HttpRequest { /* private fields */ }
Expand description

An incoming request.

Implementations§

§

impl HttpRequest

pub fn head(&self) -> &RequestHead

This method returns reference to the request head

pub fn uri(&self) -> &Uri

Request’s uri.

pub fn full_url(&self) -> Url

Returns request’s original full URL.

Reconstructed URL is best-effort, using connection_info to get forwarded scheme & host.

use actix_web::test::TestRequest;
let req = TestRequest::with_uri("http://10.1.2.3:8443/api?id=4&name=foo")
    .insert_header(("host", "example.com"))
    .to_http_request();

assert_eq!(
    req.full_url().as_str(),
    "http://example.com/api?id=4&name=foo",
);

pub fn method(&self) -> &Method

Read the Request method.

pub fn version(&self) -> Version

Read the Request Version.

pub fn headers(&self) -> &HeaderMap

Returns request’s headers.

pub fn path(&self) -> &str

The target path of this request.

pub fn query_string(&self) -> &str

The query string in the URL.

Example: id=10

pub fn match_info(&self) -> &Path<Url>

Returns a reference to the URL parameters container.

A URL parameter is specified in the form {identifier}, where the identifier can be used later in a request handler to access the matched value for that parameter.

§Percent Encoding and URL Parameters

Because each URL parameter is able to capture multiple path segments, none of ["%2F", "%25", "%2B"] found in the request URI are decoded into ["/", "%", "+"] in order to preserve path integrity. If a URL parameter is expected to contain these characters, then it is on the user to decode them or use the web::Path extractor which will decode these special sequences.

pub fn match_pattern(&self) -> Option<String>

The resource definition pattern that matched the path. Useful for logging and metrics.

For example, when a resource with pattern /user/{id}/profile is defined and a call is made to /user/123/profile this function would return Some("/user/{id}/profile").

Returns a None when no resource is fully matched, including default services.

pub fn match_name(&self) -> Option<&str>

The resource name that matched the path. Useful for logging and metrics.

Returns a None when no resource is fully matched, including default services.

pub fn conn_data<T>(&self) -> Option<&T>
where T: 'static,

Returns a reference a piece of connection data set in an on-connect callback.

let opt_t = req.conn_data::<PeerCertificate>();

pub fn url_for<U, I>( &self, name: &str, elements: U, ) -> Result<Url, UrlGenerationError>
where U: IntoIterator<Item = I>, I: AsRef<str>,

Generates URL for a named resource.

This substitutes in sequence all URL parameters that appear in the resource itself and in parent scopes, if any.

It is worth noting that the characters ['/', '%'] are not escaped and therefore a single URL parameter may expand into multiple path segments and elements can be percent-encoded beforehand without worrying about double encoding. Any other character that is not valid in a URL path context is escaped using percent-encoding.

§Examples
fn index(req: HttpRequest) -> HttpResponse {
    let url = req.url_for("foo", &["1", "2", "3"]); // <- generate URL for "foo" resource
    HttpResponse::Ok().into()
}

let app = App::new()
    .service(web::resource("/test/{one}/{two}/{three}")
         .name("foo")  // <- set resource name so it can be used in `url_for`
         .route(web::get().to(|| HttpResponse::Ok()))
    );

pub fn url_for_static(&self, name: &str) -> Result<Url, UrlGenerationError>

Generate URL for named resource

This method is similar to HttpRequest::url_for() but it can be used for urls that do not contain variable parts.

pub fn resource_map(&self) -> &ResourceMap

Get a reference to a ResourceMap of current application.

pub fn peer_addr(&self) -> Option<SocketAddr>

Returns peer socket address.

Peer address is the directly connected peer’s socket address. If a proxy is used in front of the Actix Web server, then it would be address of this proxy.

For expanded client connection information, use connection_info instead.

Will only return None when called in unit tests unless TestRequest::peer_addr is used.

pub fn connection_info(&self) -> Ref<'_, ConnectionInfo>

Returns connection info for the current request.

The return type, [ConnectionInfo], can also be used as an extractor.

§Panics

Panics if request’s extensions container is already borrowed.

pub fn app_config(&self) -> &AppConfig

Returns a reference to the application’s connection configuration.

pub fn app_data<T>(&self) -> Option<&T>
where T: 'static,

Retrieves a piece of application state.

Extracts any object stored with App::app_data() (or the counterpart methods on Scope and Resource) during application configuration.

Since the Actix Web router layers application data, the returned object will reference the “closest” instance of the type. For example, if an App stores a u32, a nested Scope also stores a u32, and the delegated request handler falls within that Scope, then calling .app_data::<u32>() on an HttpRequest within that handler will return the Scope’s instance. However, using the same router set up and a request that does not get captured by the Scope, .app_data::<u32>() would return the App’s instance.

If the state was stored using the Data wrapper, then it must also be retrieved using this same type.

See also the Data extractor.

§Examples
let opt_t: Option<&Data<T>> = req.app_data::<Data<T>>();

Trait Implementations§

§

impl Apiv2Schema for HttpRequest

§

fn name() -> Option<String>

Name of this schema. This is the name to which the definition of the object is mapped.
§

fn description() -> &'static str

Description of this schema. In case the trait is derived, uses the documentation on the type.
§

fn required() -> bool

Indicates the requirement of this schema.
§

fn raw_schema() -> DefaultSchemaRaw

Returns the raw schema for this object.
§

fn schema_with_ref() -> DefaultSchemaRaw

Returns the schema with a reference (if this is an object). Read more
§

fn security_scheme() -> Option<SecurityScheme>

Returns the security scheme for this object.
§

fn header_parameter_schema() -> Vec<Parameter<DefaultSchemaRaw>>

§

impl Clone for HttpRequest

§

fn clone(&self) -> HttpRequest

Returns a copy of the value. Read more
1.0.0 · source§

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

Performs copy-assignment from source. Read more
§

impl Debug for HttpRequest

§

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

Formats the value using the given formatter. Read more
§

impl Drop for HttpRequest

§

fn drop(&mut self)

Executes the destructor for this type. Read more
§

impl FromRequest for HttpRequest

It is possible to get HttpRequest as an extractor handler parameter

§Examples

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

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

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

type Error = Error

The associated error which can be returned.
§

type Future = Ready<Result<HttpRequest, Error>>

Future that resolves to a Self. Read more
§

fn from_request( req: &HttpRequest, _: &mut Payload, ) -> <HttpRequest as FromRequest>::Future

Create a Self from request parts asynchronously.
§

fn extract(req: &HttpRequest) -> Self::Future

Create a Self from request head asynchronously. Read more
§

impl HttpMessage for HttpRequest

§

type Stream = ()

Type of message payload stream
§

fn headers(&self) -> &HeaderMap

Read the message headers.
§

fn extensions(&self) -> Ref<'_, Extensions>

Returns a reference to the request-local data/extensions container.
§

fn extensions_mut(&self) -> RefMut<'_, Extensions>

Returns a mutable reference to the request-local data/extensions container.
§

fn take_payload(&mut self) -> Payload<<HttpRequest as HttpMessage>::Stream>

Message payload stream
§

fn content_type(&self) -> &str

Read the request content type. If request did not contain a Content-Type header, an empty string is returned.
§

fn encoding(&self) -> Result<&'static Encoding, ContentTypeError>

Get content type encoding. Read more
§

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.
§

impl OperationModifier for HttpRequest

§

fn update_parameter( op: &mut Operation<Parameter<DefaultSchemaRaw>, Response<DefaultSchemaRaw>>, )

Update the parameters list in the given operation (if needed).
§

fn update_response( _op: &mut Operation<Parameter<DefaultSchemaRaw>, Response<DefaultSchemaRaw>>, )

Update the responses map in the given operation (if needed).
§

fn update_definitions(map: &mut BTreeMap<String, DefaultSchemaRaw>)

Update the definitions map (if needed).
§

fn update_security( op: &mut Operation<Parameter<DefaultSchemaRaw>, Response<DefaultSchemaRaw>>, )

Update the security map in the given operation (if needed).
§

fn update_security_definitions(map: &mut BTreeMap<String, SecurityScheme>)

Update the security definition map (if needed).

Auto Trait Implementations§

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> 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<T> CloneToUninit for T
where T: Clone,

source§

unsafe fn clone_to_uninit(&self, dst: *mut T)

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

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

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

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

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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.
§

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

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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