用axum写个简单应用
时间: 2024-11-20 11:44:40 浏览: 18
Axum是一个轻量级、易学的Rust Web框架,用于构建高性能的Web服务。下面是一个简单的Axum应用示例:
```rust
// 首先,你需要在Cargo.toml文件中添加对axum的依赖
[dependencies]
axum = "0.9"
actix-web = { version = "3", features = ["full"] }
reqwest = "0.11"
// 然后创建一个main.rs文件并添加以下代码
use axum::{Router, RouterError};
use actix_web::{web, App, Error};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// 创建一个路由器
let mut app = Router::new();
// 添加一个GET请求处理函数
app.route("/hello", web::get().to(hello_world));
// 定义hello_world函数,它将返回一个"Hello, world!"响应
async fn hello_world() -> Result<String, Error> {
Ok("Hello, world!".into())
}
// 启动服务器监听8080端口
HttpServer::bind("127.0.0.1:8080").serve(app.into_make_service())?;
println!("Server is running on http://localhost:8080");
Ok(())
}
```
这个例子中,我们创建了一个简单的HTTP服务器,监听`/hello`路径的GET请求,并返回固定的字符串"Hello, world!"。运行这个程序后,访问`http://localhost:8080/hello`就会看到这个消息。
阅读全文
相关推荐














