Unable to implement IntoResponse for custom body #1191
-
I have a custom response body as: use axum::response::{IntoResponse, Response};
use serde::{Serialize, Deserialize};
#[derive(Debug, Serialize, Deserialize)]
pub struct ResponseBody<T> {
pub message: String,
pub data: T,
}
impl<T> ResponseBody<T> {
pub fn new(message: &str, data: T) -> ResponseBody<T> {
ResponseBody {
message: message.to_string(),
data,
}
}
} I want to implement pub async fn signin (
Json(login_form): Json<LoginForm>,
pool: Extension<Pool>
) -> Response {
// output should be a json response
match user::signin(login_form, &pool) {
Ok(token_res) => Json(json!(ResponseBody::new(constants::MESSAGE_SIGNIN_SUCCESS, token_res))).into_response(),,
Err(err) => Ok(err.response()), // this is prompting error
}
} In above function I need to return a Json response. Also, the #[derive(Debug)]
pub struct ServiceError {
pub http_status: StatusCode,
pub body: ResponseBody<String>,
}
impl ServiceError {
pub fn new(http_status: StatusCode, message: String) -> ServiceError {
ServiceError {
http_status,
body: ResponseBody {
message,
data: String::new(), // try box body, in this see if you can implement HttpResponse like service, post on axum
},
}
}
// pub fn response(&self) -> impl IntoResponse {
// // use json as extractor
// let jsonbody = json!(self.body);
// let response: Response<BoxBody>= Json(jsonbody).into_response();
// (
// self.http_status,
// jsonbody,
// ).into_response()
// } Also, I referred to the official documentation of IntoResponse for the custom body type, but it wasn't much beneficial for me since I am a beginner for the concept |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
It sounds like you're misunderstanding some concepts:
From the code you posted it looks like you just wanna return some For |
Beta Was this translation helpful? Give feedback.
It sounds like you're misunderstanding some concepts:
http_body::Body
. This is a low level trait that requires dealing with pinning and such. Response bodies cannot set headers since its just a body. I don't think this is what you're looking for.IntoResponse
. It can set status, headers, and response body.Json
is a response that will convert someT: serde::Serialize
intoJSON
, set acontent-type: application/json
header, and return that.From the code you posted it looks like you just wanna return some
JSON
. In which case you should just useaxum::Json(...)
. Just make sure your type implementsserde::S…