Aviral Srivastava
Aviral Srivastava

Reputation: 4582

Why does returning `&'static str` from an Axum handler show on a web page but `print!` or `format!` does not?

While creating a simple web server using axum, I was able to flush the output on a route that leverages a function of return type &'static str but not with a function that just print!s the string.

use axum::routing::get;
use axum::Router;

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

    axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
        .serve(app.into_make_service())
        .await
        .unwrap();
}

async fn root() -> &'static str {
    "Functional call is root"
}

async fn avi() {
    print!("Functional call is avi")
}

When visiting localhost:3000/avi, nothing gets printed on the screen. However, when visiting localhost:3000, the corresponding output Functional call is root gets printed.

Upvotes: 0

Views: 629

Answers (1)

kmdreko
kmdreko

Reputation: 60507

The value you return from your Axum handlers determine what is sent back to the client. In the case of returning &str (as your root() handler does), it will return a successful response with that string as the content. In the case of returning () (as your avi() handler does), it will return a successful response but with no content.

The output of print! does not factor in because it is never directed to a source other than stdout. If you run your program in a local terminal, you'd see "Functional call is avi" in the terminal.

Upvotes: 4

Related Questions