use crate::axum::body::Body;
use crate::axum::response::Response;
use http::StatusCode;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Format {
Html,
Json,
Any,
}
pub struct RespondTo {
format: Format,
response: Option<Response>,
}
impl RespondTo {
pub fn new(format: Format) -> Self {
Self {
format,
response: None,
}
}
pub fn html(mut self, f: impl FnOnce() -> Response) -> Self {
if self.response.is_none() && matches!(self.format, Format::Html | Format::Any) {
self.response = Some(f());
}
self
}
pub fn json(mut self, f: impl FnOnce() -> Response) -> Self {
if self.response.is_none() && matches!(self.format, Format::Json | Format::Any) {
self.response = Some(f());
}
self
}
pub fn finish(self) -> Response {
self.response.unwrap_or_else(|| {
Response::builder()
.status(StatusCode::NOT_ACCEPTABLE)
.body(Body::empty())
.expect("valid 406 response")
})
}
}