use {
axum::{
extract::Request,
http::{header::*, *},
response::{Response, *},
},
kutil::std::immutable::*,
};
#[derive(Clone, Debug)]
pub enum DeferredResponse {
Hide,
Authenticate(ByteString),
RedirectTo((ByteString, StatusCode)),
RewriteFrom(ByteString),
Error(ByteString),
}
impl DeferredResponse {
pub fn get(request: &Request) -> Option<&Self> {
request.extensions().get()
}
pub fn authenticate(authenticate: &str) -> Response {
(StatusCode::UNAUTHORIZED, [(WWW_AUTHENTICATE, authenticate)]).into_response()
}
pub fn redirect_to(uri_path: &str, status_code: StatusCode) -> Response {
assert!(status_code.is_redirection());
(status_code, [(LOCATION, uri_path)]).into_response()
}
}
pub trait WithDeferredResponse {
fn with_deferred_response(self, delayed_response: DeferredResponse) -> Self;
fn with_deferred_hide(self) -> Self;
fn with_deferred_authenticate(self, authenticate: ByteString) -> Self;
fn with_deferred_redirect_to(self, uri_path: ByteString, status_code: StatusCode) -> Self;
fn with_deferred_rewrite_from(self, uri_path: ByteString) -> Self;
fn with_deferred_error(self, error: ByteString) -> Self;
}
impl WithDeferredResponse for Request {
fn with_deferred_response(mut self, delayed_response: DeferredResponse) -> Self {
self.extensions_mut().insert(delayed_response);
self
}
fn with_deferred_hide(self) -> Self {
self.with_deferred_response(DeferredResponse::Hide)
}
fn with_deferred_authenticate(self, authenticate: ByteString) -> Self {
self.with_deferred_response(DeferredResponse::Authenticate(authenticate))
}
fn with_deferred_redirect_to(self, uri_path: ByteString, status_code: StatusCode) -> Self {
assert!(status_code.is_redirection());
self.with_deferred_response(DeferredResponse::RedirectTo((uri_path, status_code)))
}
fn with_deferred_rewrite_from(self, uri_path: ByteString) -> Self {
self.with_deferred_response(DeferredResponse::RewriteFrom(uri_path))
}
fn with_deferred_error(self, error: ByteString) -> Self {
self.with_deferred_response(DeferredResponse::Error(error))
}
}