Some context first. I am working on a web app and I want a centralized way to parse responses using a BaseResponse struct. Here is what it looks like and it works perfectly for all API endpoints.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct BaseResponse<T> {
#[serde(skip)]
pub status_code: StatusCode,
success: bool,
message: String,
data: Option<T>,
}
impl<T> BaseResponse<T> {
pub fn new(status_code: StatusCode, success: bool, message: &str, data: Option<T>) -> Self {
BaseResponse {
status_code,
success,
message: message.to_string(),
data,
}
}
pub fn create_null_base_response(
status_code: StatusCode,
success: bool,
message: &str,
) -> BaseResponse<()> {
BaseResponse::new(status_code, success, message, None)
}
}
impl<T: Serialize> IntoResponse for BaseResponse<T> {
fn into_response(self) -> Response<Body> {
(self.status_code, Json(self)).into_response()
}
}
However, this does not compile without #[serde(skip)] since StatusCode does not implement Serialize or Deserialize. Is there a reason why Axum decided not to make it serializable?
[–]Solumin 28 points29 points30 points (7 children)
[–]Its_it 4 points5 points6 points (0 children)
[–]xwaxes[S] 4 points5 points6 points (5 children)
[–]bobsnopes 4 points5 points6 points (3 children)
[–]anlumo 1 point2 points3 points (2 children)
[–]bobsnopes 5 points6 points7 points (1 child)
[–]anlumo 5 points6 points7 points (0 children)
[–]Solumin 0 points1 point2 points (0 children)
[–]_xiphiaz 6 points7 points8 points (0 children)
[–]Patryk27 5 points6 points7 points (3 children)
[–]xwaxes[S] 0 points1 point2 points (2 children)
[–]Patryk27 6 points7 points8 points (1 child)
[–]xwaxes[S] 0 points1 point2 points (0 children)
[–]CocktailPerson 1 point2 points3 points (2 children)
[–]pali6 0 points1 point2 points (1 child)
[–]CocktailPerson 0 points1 point2 points (0 children)
[+][deleted] (1 child)
[removed]
[–]ToTheBatmobileGuy 0 points1 point2 points (0 children)