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 desireable 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
Trait Implementations
impl<L, R> FromRequest for Either<L, R> where
L: FromRequest + 'static,
R: FromRequest + 'static,
impl<L, R> FromRequest for Either<L, R> where
L: FromRequest + 'static,
R: FromRequest + 'static,
See here for example of usage as an extractor.
Auto Trait Implementations
impl<L, R> RefUnwindSafe for Either<L, R> where
L: RefUnwindSafe,
R: RefUnwindSafe,
impl<L, R> UnwindSafe for Either<L, R> where
L: UnwindSafe,
R: UnwindSafe,
Blanket Implementations
Mutably borrows from an owned value. Read more
pub fn vzip(self) -> V
Attaches the provided Subscriber
to this type, returning a
WithDispatch
wrapper. Read more
Attaches the current default Subscriber
to this type, returning a
WithDispatch
wrapper. Read more