Axum. Return different messages through IntoResponse

I use axum and I have the next function which returns status and Json,

async fn create_message(
&self,
Json(payload): Json,
) -> impl IntoResponse {
let mut message = Request {
data: "123",
};
(StatusCode::OK, Json(message))
}

But I need to return depends on situation different messages. For example
let mut message1 = Request1 {
layer: "123",
};

    let mut message2 = Request2 {
        info: "123",
    };

But I do not know how to return different messages via IntoResponse. Could you help me?

1 Like

You can just call into_response on the values yourself before returning them

Do you mean like this
fn into_response(self) -> Response < Self::Body >
{
Response::new()
}
?
Could you add more explanation? Or any example?

The trait axum uses to build a response from your handler is IntoResponse. Your function currently returns impl IntoResponse which means it returns some type that implements the trait, but we aren't specifying which type it is.

Since impl IntoResponse only supports returning a single type, we can just call the method that builds the reponse ourselves before we return. Then we can return the actual response type, which is the same for all responses.

use axum::{
    extract::Path,
    http::StatusCode,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let app = Router::new().route("/:path", get(handle));

    let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn handle(Path(path): Path<String>) -> Response {
    if path.len() < 5 {
        (StatusCode::BAD_REQUEST, "Short path").into_response()
    } else {
        StatusCode::OK.into_response()
    }
}
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.