面试题答案
一键面试实现思路
- 选择合适的Web框架:Rust中有多个Web框架可用于构建Web服务器,如
actix-web
、rocket
等。这里以actix-web
为例,它是一个基于actix
生态系统的高性能Web框架。 - 定义路由:在框架中定义不同URL路径对应的处理函数。每个处理函数负责生成特定的响应内容。
- 启动服务器:将定义好的路由绑定到服务器,并启动服务器监听指定端口。
关键代码片段
- 引入依赖:在
Cargo.toml
文件中添加actix-web
依赖:
[dependencies]
actix-web = "4.0"
- 编写主程序:
use actix_web::{get, App, HttpResponse, HttpServer, Responder};
// 处理根路径的函数
#[get("/")]
async fn index() -> impl Responder {
HttpResponse::Ok().body("Welcome to the simple web server!")
}
// 处理 /about 路径的函数
#[get("/about")]
async fn about() -> impl Responder {
HttpResponse::Ok().body("This is an about page.")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(index)
.service(about)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
在上述代码中,通过#[get("/")]
和#[get("/about")]
分别定义了根路径和/about
路径的处理函数index
和about
。HttpServer::new
创建一个新的服务器实例,并将定义好的路由添加到应用中,最后绑定到127.0.0.1:8080
并运行。