Module axum_extra::either

source ·
Expand description

Either* types for combining extractors or responses into a single type.

§As an extractor

use axum_extra::either::Either3;
use axum::{
    body::Bytes,
    Router,
    async_trait,
    routing::get,
    extract::FromRequestParts,
};

// extractors for checking permissions
struct AdminPermissions {}

#[async_trait]
impl<S> FromRequestParts<S> for AdminPermissions
where
    S: Send + Sync,
{
    // check for admin permissions...
}

struct User {}

#[async_trait]
impl<S> FromRequestParts<S> for User
where
    S: Send + Sync,
{
    // check for a logged in user...
}

async fn handler(
    body: Either3<AdminPermissions, User, ()>,
) {
    match body {
        Either3::E1(admin) => { /* ... */ }
        Either3::E2(user) => { /* ... */ }
        Either3::E3(guest) => { /* ... */ }
    }
}

Note that if all the inner extractors reject the request, the rejection from the last extractor will be returned. For the example above that would be BytesRejection.

§As a response

use axum_extra::either::Either3;
use axum::{Json, http::StatusCode, response::IntoResponse};
use serde_json::{Value, json};

async fn handler() -> Either3<Json<Value>, &'static str, StatusCode> {
    if something() {
        Either3::E1(Json(json!({ "data": "..." })))
    } else if something_else() {
        Either3::E2("foobar")
    } else {
        Either3::E3(StatusCode::NOT_FOUND)
    }
}

fn something() -> bool {
    // ...
}

fn something_else() -> bool {
    // ...
}

The general recommendation is to use IntoResponse::into_response to return different response types, but if you need to preserve the exact type then Either* works as well.

Enums§

  • Combines two extractors or responses into a single type.
  • Combines three extractors or responses into a single type.
  • Combines four extractors or responses into a single type.
  • Combines five extractors or responses into a single type.
  • Combines six extractors or responses into a single type.
  • Combines seven extractors or responses into a single type.
  • Combines eight extractors or responses into a single type.