面试题答案
一键面试在Actix Web中定义和处理不同路由的步骤如下:
- 引入必要的依赖:在
Cargo.toml
文件中添加actix-web
依赖。
[dependencies]
actix-web = "4.0.0"
- 创建简单的GET请求路由并返回固定响应:
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
// 处理函数,返回固定响应
#[get("/")]
async fn index() -> impl Responder {
HttpResponse::Ok().body("Hello, World!")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(index)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
在上述代码中:
#[get("/")]
宏定义了一个GET请求的路由,路径为/
。index
函数是处理该路由的函数,它返回一个实现了Responder
trait的类型,这里返回HttpResponse::Ok().body("Hello, World!")
,即返回HTTP 200状态码,并带有文本内容Hello, World!
。- 在
main
函数中,使用HttpServer
创建一个HTTP服务器,将index
服务注册到应用程序中,并绑定到127.0.0.1:8080
地址上运行。