mirror of
https://github.com/fafhrd91/actix-web
synced 2025-08-31 00:50:20 +02:00
add either extractor (#1788)
This commit is contained in:
@@ -332,82 +332,6 @@ impl<T: Responder> Future for CustomResponderFut<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Combines two different responder types into a single type
|
||||
///
|
||||
/// ```rust
|
||||
/// use actix_web::{Either, Error, HttpResponse};
|
||||
///
|
||||
/// type RegisterResult = Either<HttpResponse, Result<HttpResponse, Error>>;
|
||||
///
|
||||
/// fn index() -> RegisterResult {
|
||||
/// if is_a_variant() {
|
||||
/// // <- choose left variant
|
||||
/// Either::A(HttpResponse::BadRequest().body("Bad data"))
|
||||
/// } else {
|
||||
/// Either::B(
|
||||
/// // <- Right variant
|
||||
/// Ok(HttpResponse::Ok()
|
||||
/// .content_type("text/html")
|
||||
/// .body("Hello!"))
|
||||
/// )
|
||||
/// }
|
||||
/// }
|
||||
/// # fn is_a_variant() -> bool { true }
|
||||
/// # fn main() {}
|
||||
/// ```
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Either<A, B> {
|
||||
/// First branch of the type
|
||||
A(A),
|
||||
/// Second branch of the type
|
||||
B(B),
|
||||
}
|
||||
|
||||
impl<A, B> Responder for Either<A, B>
|
||||
where
|
||||
A: Responder,
|
||||
B: Responder,
|
||||
{
|
||||
type Error = Error;
|
||||
type Future = EitherResponder<A, B>;
|
||||
|
||||
fn respond_to(self, req: &HttpRequest) -> Self::Future {
|
||||
match self {
|
||||
Either::A(a) => EitherResponder::A(a.respond_to(req)),
|
||||
Either::B(b) => EitherResponder::B(b.respond_to(req)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[pin_project(project = EitherResponderProj)]
|
||||
pub enum EitherResponder<A, B>
|
||||
where
|
||||
A: Responder,
|
||||
B: Responder,
|
||||
{
|
||||
A(#[pin] A::Future),
|
||||
B(#[pin] B::Future),
|
||||
}
|
||||
|
||||
impl<A, B> Future for EitherResponder<A, B>
|
||||
where
|
||||
A: Responder,
|
||||
B: Responder,
|
||||
{
|
||||
type Output = Result<Response, Error>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
match self.project() {
|
||||
EitherResponderProj::A(fut) => {
|
||||
Poll::Ready(ready!(fut.poll(cx)).map_err(|e| e.into()))
|
||||
}
|
||||
EitherResponderProj::B(fut) => {
|
||||
Poll::Ready(ready!(fut.poll(cx).map_err(|e| e.into())))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Responder for InternalError<T>
|
||||
where
|
||||
T: std::fmt::Debug + std::fmt::Display + 'static,
|
||||
|
Reference in New Issue
Block a user