Either

Enum Either 

pub enum Either<L, R> {
    Left(L),
    Right(R),
}
Expand description

Combines two extractor or responder types into a single type.

§Extractor

Provides a mechanism for trying two extractors, a primary and a fallback. Useful for “polymorphic payloads” where, for example, a form might be JSON or URL encoded.

It is important to note that this extractor, by necessity, buffers the entire request payload as part of its implementation. Though, it does respect any PayloadConfig maximum size limits.

use actix_web::{post, web, Either};
use serde::Deserialize;

#[derive(Deserialize)]
struct Info {
    name: String,
}

// handler that accepts form as JSON or form-urlencoded.
#[post("/")]
async fn index(form: Either<web::Json<Info>, web::Form<Info>>) -> String {
    let name: String = match form {
        Either::Left(json) => json.name.to_owned(),
        Either::Right(form) => form.name.to_owned(),
    };

    format!("Welcome {}!", name)
}

§Responder

It may be desirable to use a concrete type for a response with multiple branches. As long as both types implement Responder, so will the Either type, enabling it to be used as a handler’s return type.

All properties of a response are determined by the Responder branch returned.

use actix_web::{get, Either, Error, HttpResponse};

#[get("/")]
async fn index() -> Either<&'static str, Result<HttpResponse, Error>> {
    if 1 == 2 {
        // respond with Left variant
        Either::Left("Bad data")
    } else {
        // respond with Right variant
        Either::Right(
            Ok(HttpResponse::Ok()
                .content_type(mime::TEXT_HTML)
                .body("<p>Hello!</p>"))
        )
    }
}

Variants§

§

Left(L)

A value of type L.

§

Right(R)

A value of type R.

Implementations§

§

impl<T> Either<Form<T>, Json<T>>

pub fn into_inner(self) -> T

§

impl<T> Either<Json<T>, Form<T>>

pub fn into_inner(self) -> T

Trait Implementations§

§

impl<L, R> Debug for Either<L, R>
where L: Debug, R: Debug,

§

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

Formats the value using the given formatter. Read more
§

impl<L, R> FromRequest for Either<L, R>
where L: FromRequest + 'static, R: FromRequest + 'static,

See here for example of usage as an extractor.

§

type Error = EitherExtractError<<L as FromRequest>::Error, <R as FromRequest>::Error>

The associated error which can be returned.
§

type Future = EitherExtractFut<L, R>

Future that resolves to a Self. Read more
§

fn from_request( req: &HttpRequest, payload: &mut Payload, ) -> <Either<L, R> 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<L, R> PartialEq for Either<L, R>
where L: PartialEq, R: PartialEq,

§

fn eq(&self, other: &Either<L, R>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
§

impl<L, R> Responder for Either<L, R>
where L: Responder, R: Responder,

See here for example of usage as a handler return type.

§

type Body = EitherBody<<L as Responder>::Body, <R as Responder>::Body>

§

fn respond_to( self, req: &HttpRequest, ) -> HttpResponse<<Either<L, R> as Responder>::Body>

Convert self to HttpResponse.
§

fn customize(self) -> CustomizeResponder<Self>
where Self: Sized,

Wraps responder to allow alteration of its response. Read more
§

impl<L, R> Eq for Either<L, R>
where L: Eq, R: Eq,

§

impl<L, R> StructuralPartialEq for Either<L, R>

Auto Trait Implementations§

§

impl<L, R> Freeze for Either<L, R>
where L: Freeze, R: Freeze,

§

impl<L, R> RefUnwindSafe for Either<L, R>

§

impl<L, R> Send for Either<L, R>
where L: Send, R: Send,

§

impl<L, R> Sync for Either<L, R>
where L: Sync, R: Sync,

§

impl<L, R> Unpin for Either<L, R>
where L: Unpin, R: Unpin,

§

impl<L, R> UnwindSafe for Either<L, R>
where L: UnwindSafe, R: UnwindSafe,

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
§

impl<T> Chain<T> for T

§

fn len(&self) -> usize

The number of items that this chain link consists of.
§

fn append_to(self, v: &mut Vec<T>)

Append the elements in this link to the chain.
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. 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> 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
§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

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

Initializes a with the given initializer. Read more
§

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

Dereferences the given pointer. Read more
§

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

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

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

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: 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
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: 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> Same for T

Source§

type Output = T

Should always be Self
§

impl<T> ServiceExt for T

§

fn map_response_body<F>(self, f: F) -> MapResponseBody<Self, F>
where Self: Sized,

Apply a transformation to the response body. Read more
§

fn decompression(self) -> Decompression<Self>
where Self: Sized,

Decompress response bodies. Read more
§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the Standard policy. 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
§

impl<T> ErasedDestructor for T
where T: 'static,