英文:
Why does returning `&'static str` from an Axum handler show on a web page but `print!` or `format!` does not?
问题
在使用 Axum 创建一个简单的 Web 服务器时,我能够在一个返回类型为 &'static str
的函数的路由上刷新输出,但不能在一个只是使用 print!
打印字符串的函数上刷新输出。
当访问 localhost:3000/avi
时,屏幕上不会打印任何内容。然而,当访问 localhost:3000
时,相应的输出 Functional call is root
会被打印出来。
英文:
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.
答案1
得分: 4
从您的Axum处理程序返回的值确定发送回客户端的内容。在返回&str
(就像您的root()
处理程序一样)的情况下,它将返回一个带有该字符串作为内容的成功响应。在返回()
(就像您的avi()
处理程序一样)的情况下,它将返回一个成功的响应,但没有内容。
print!
的输出不会被考虑,因为它从未被定向到除标准输出之外的其他源。如果您在本地终端中运行程序,您将在终端中看到"Functional call is avi"
。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论