paperclip_actix::web

Struct Data

pub struct Data<T>(/* private fields */)
where
    T: ?Sized;
Expand description

Application data wrapper and extractor.

§Setting Data

Data is set using the app_data methods on App, Scope, and Resource. If data is wrapped in this Data type for those calls, it can be used as an extractor.

Note that Data should be constructed outside the HttpServer::new closure if shared, potentially mutable state is desired. Data is cheap to clone; internally, it uses an Arc.

See also App::app_data, Scope::app_data, and Resource::app_data.

§Extracting Data

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 extracting a web::Data<u32> for 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, web::<Data<u32>> would return the App’s instance.

If route data is not set for a handler, using Data<T> extractor would cause a 500 Internal Server Error response.

See also HttpRequest::app_data and ServiceRequest::app_data.

§Unsized Data

For types that are unsized, most commonly dyn T, Data can wrap these types by first constructing an Arc<dyn T> and using the From implementation to convert it.

let displayable_arc: Arc<dyn Display> = Arc::new(42usize);
let displayable_data: Data<dyn Display> = Data::from(displayable_arc);

§Examples

use std::sync::Mutex;
use actix_web::{App, HttpRequest, HttpResponse, Responder, web::{self, Data}};

struct MyData {
    counter: usize,
}

/// Use the `Data<T>` extractor to access data in a handler.
async fn index(data: Data<Mutex<MyData>>) -> impl Responder {
    let mut my_data = data.lock().unwrap();
    my_data.counter += 1;
    HttpResponse::Ok()
}

/// Alternatively, use the `HttpRequest::app_data` method to access data in a handler.
async fn index_alt(req: HttpRequest) -> impl Responder {
    let data = req.app_data::<Data<Mutex<MyData>>>().unwrap();
    let mut my_data = data.lock().unwrap();
    my_data.counter += 1;
    HttpResponse::Ok()
}

let data = Data::new(Mutex::new(MyData { counter: 0 }));

let app = App::new()
    // Store `MyData` in application storage.
    .app_data(Data::clone(&data))
    .route("/index.html", web::get().to(index))
    .route("/index-alt.html", web::get().to(index_alt));

Implementations§

§

impl<T> Data<T>

pub fn new(state: T) -> Data<T>

Create new Data instance.

§

impl<T> Data<T>
where T: ?Sized,

pub fn get_ref(&self) -> &T

Returns reference to inner T.

pub fn into_inner(self) -> Arc<T>

Unwraps to the internal Arc<T>

Trait Implementations§

§

impl<T> Apiv2Schema for Data<T>

§

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<T> Clone for Data<T>
where T: ?Sized,

§

fn clone(&self) -> Data<T>

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<T> Debug for Data<T>
where T: Debug + ?Sized,

§

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

Formats the value using the given formatter. Read more
§

impl<T> Default for Data<T>
where T: Default,

§

fn default() -> Data<T>

Returns the “default value” for a type. Read more
§

impl<T> Deref for Data<T>
where T: ?Sized,

§

type Target = Arc<T>

The resulting type after dereferencing.
§

fn deref(&self) -> &Arc<T>

Dereferences the value.
§

impl<'de, T> Deserialize<'de> for Data<T>
where T: Deserialize<'de>,

§

fn deserialize<D>( deserializer: D, ) -> Result<Data<T>, <D as Deserializer<'de>>::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
§

impl<T> From<Arc<T>> for Data<T>
where T: ?Sized,

§

fn from(arc: Arc<T>) -> Data<T>

Converts to this type from the input type.
§

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

§

type Error = Error

The associated error which can be returned.
§

type Future = Ready<Result<Data<T>, Error>>

Future that resolves to a Self. Read more
§

fn from_request( req: &HttpRequest, _: &mut Payload, ) -> <Data<T> 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<T> OperationModifier for Data<T>

§

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

impl<T> Serialize for Data<T>
where T: Serialize,

§

fn serialize<S>( &self, serializer: S, ) -> Result<<S as Serializer>::Ok, <S as Serializer>::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Data<T>
where T: ?Sized,

§

impl<T> RefUnwindSafe for Data<T>
where T: RefUnwindSafe + ?Sized,

§

impl<T> Send for Data<T>
where T: Sync + Send + ?Sized,

§

impl<T> Sync for Data<T>
where T: Sync + Send + ?Sized,

§

impl<T> Unpin for Data<T>
where T: ?Sized,

§

impl<T> UnwindSafe for Data<T>
where T: RefUnwindSafe + ?Sized,

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

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<T> Formattable for T
where T: Deref, <T as Deref>::Target: Formattable,