30天拿下Rust之实战Web Server

}



#### 处理JSON请求


        对于API服务,经常需要处理JSON格式的请求与响应。修改Cargo.toml文件,引入serde和serde\_json来简化工作。



[dependencies]
actix-web = { version = “4.5.0”}
serde = { version = “1”, features = [“derive”] }
serde_json = “1”


        在下面的示例代码中,我们首先导入了serde库中的Deserialize和Serialize特质,它们用于定义结构体可以被自动序列化和反序列化为JSON格式。


        然后,定义了一个名为FormData的结构体,它有一个字段field\_name,类型为String。通过derive属性,该结构体获得了从JSON字符串自动反序列化(Deserialize)的能力,以及将自身序列化为JSON字符串(Serialize)的能力,Debug特征使得结构体可以方便地输出调试信息。我们还定义了一个名为JsonResponse的结构体,它有一个字段message,类型也为String。这里只应用了Serialize特质,因为这个结构体是用来构造返回给客户端的JSON响应报文的,不需要反序列化能力。


        最后,我们定义了处理POST请求的异步函数handle\_post,它接受一个类型为web::Json<FormData>的参数。web::Json是一个wrapper类型,表示请求体应该被解析为FormData结构体。函数内部首先打印接收到的POST数据,然后创建一个JsonResponse实例,其中message字段内容为"Hello from Rust Server"。函数的最后,返回一个201 Created状态码的响应,主体内容为序列化后的JsonResponse实例。



use actix_web::{web, App, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug)]
struct FormData {
field_name: String,
}

#[derive(Serialize)]
struct JsonResponse {
message: String,
}

async fn index() -> HttpResponse {
HttpResponse::Ok().body(“Hello Rust”)
}

async fn new_route_handler() -> HttpResponse {
HttpResponse::Ok().body(“New route handler”)
}

async fn handle_post(form_data: web::Json) -> Result {
println!(“Received POST data: {:?}”, form_data.into_inner());
let response_data = JsonResponse {
message: format!(“Hello from {}”, “Rust Server”.to_string()),
};
Ok(HttpResponse::Created().json(response_data))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route(“/”, web::get().to(index))
.route(“/new_route”, web::get().to(new_route_handler))
.route(“/post_data”, web::post().to(handle_post))
})
.bind(“127.0.0.1:8080”)?
.run()
.await
}


        在命令行中运行cargo run来启动程序,此时服务器开始监听localhost:8080。我们可以使用Postman来模拟浏览器发送POST请求的行为,方法选择POST,路径为localhost:8080/post\_data,Body选择raw/JSON,输入:{"field\_name": "Hello from client"}。点击Send按钮,我们会收到Rust Web Server返回的POST响应,Body为:{"message": "Hello from Rust Server"}。


![](https://img-blog.csdnimg.cn/direct/74b02607365540e4a73e4540cdec2510.png)



#### 处理动态路由参数


        要实现动态路由参数,我们可以使用actix-web提供的路径参数功能。路径参数允许我们在URL路径中定义占位符,这些占位符在请求到来时会被解析为具体的值。


        在下面的示例代码中,我们新增了一个异步函数handle\_dynamic\_route,它接受一个类型为web::Path<String>的参数。web::Path<T>是actix-web提供的一个类型,用于捕获路径参数。这里我们使用String类型来捕获动态路由中的ID。接着,在应用程序配置中,我们添加了一个新的路由。这里的/{id}路径模板中,{id}是一个占位符,表示任何非斜杠字符组成的字符串。当一个请求到达,其URL路径匹配/{id}模板时,actix-web会将路径中对应的值作为web::Path<String>传递给handle\_dynamic\_route函数。



use actix_web::{web, App, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, Debug)]
struct FormData {
field_name: String,
}

#[derive(Serialize)]
struct JsonResponse {
message: String,
}

async fn index() -> HttpResponse {
HttpResponse::Ok().body(“Hello Rust”)
}

async fn new_route_handler() -> HttpResponse {
HttpResponse::Ok().body(“New route handler”)
}

async fn handle_post(form_data: web::Json) -> Result {
println!(“Received POST data: {:?}”, form_data.into_inner());
let response_data = JsonResponse {
message: format!(“Hello from {}”, “Rust Server”.to_string()),
};
Ok(HttpResponse::Created().json(response_data))
}

async fn handle_dynamic_route(id: web::Path) -> HttpResponse {
HttpResponse::Ok().body(format!(
“Process dynamic route with ID: {}”,
id.into_inner()
))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.route(“/”, web::get().to(index))
.route(“/new_route”, web::get().to(new_route_handler))
.route(“/post_data”, web::post().to(handle_post))
.route(“/{id}”, web::get().to(handle_dynamic_route))
})
.bind(“127.0.0.1:8080”)?
.run()
.await
}


        我们仍使用Postman来模拟浏览器的动态路由参数,方法选择GET,路径为localhost:8080/666,Body选择none。点击Send按钮,我们会收到Rust Web Server返回的GET响应,Body为:Process dynamic route with ID: 666。


![](https://img-blog.csdnimg.cn/direct/34610831a47949b89491861912a3596f.png)



#### 总结


        在本文中,我们不仅搭建了一个基础的Web服务器,还实现了路由、JSON请求、动态路由参数等功能。Rust凭借其严谨的安全模型、出色的性能和丰富的生态系统,为构建高效、安全的Web服务器提供了坚实的基础。






还有兄弟不知道网络安全面试可以提前刷题吗?费时一周整理的160+网络安全面试题,金九银十,做网络安全面试里的显眼包!


王岚嵚工程师面试题(附答案),只能帮兄弟们到这儿了!如果你能答对70%,找一个安全工作,问题不大。


对于有1-3年工作经验,想要跳槽的朋友来说,也是很好的温习资料!


【完整版领取方式在文末!!】


***93道网络安全面试题***


![](https://img-blog.csdnimg.cn/img_convert/6679c89ccd849f9504c48bb02882ef8d.png)








![](https://img-blog.csdnimg.cn/img_convert/07ce1a919614bde78921fb2f8ddf0c2f.png)





![](https://img-blog.csdnimg.cn/img_convert/44238619c3ba2d672b5b8dc4a529b01d.png)





内容实在太多,不一一截图了


### 黑客学习资源推荐


最后给大家分享一份全套的网络安全学习资料,给那些想学习 网络安全的小伙伴们一点帮助!


对于从来没有接触过网络安全的同学,我们帮你准备了详细的学习成长路线图。可以说是最科学最系统的学习路线,大家跟着这个大的方向学习准没问题。


😝朋友们如果有需要的话,可以联系领取~

#### 1️⃣零基础入门


##### ① 学习路线


对于从来没有接触过网络安全的同学,我们帮你准备了详细的**学习成长路线图**。可以说是**最科学最系统的学习路线**,大家跟着这个大的方向学习准没问题。


![image](https://img-blog.csdnimg.cn/img_convert/acb3c4714e29498573a58a3c79c775da.gif#pic_center)


##### ② 路线对应学习视频


同时每个成长路线对应的板块都有配套的视频提供:


![image-20231025112050764](https://img-blog.csdnimg.cn/874ad4fd3dbe4f6bb3bff17885655014.png#pic_center)


#### 2️⃣视频配套工具&国内外网安书籍、文档


##### ① 工具


![](https://img-blog.csdnimg.cn/img_convert/d3f08d9a26927e48b1332a38401b3369.png#pic_center)


##### ② 视频


![image1](https://img-blog.csdnimg.cn/img_convert/f18acc028dc224b7ace77f2e260ba222.png#pic_center)


##### ③ 书籍


![image2](https://img-blog.csdnimg.cn/img_convert/769b7e13b39771b3a6e4397753dab12e.png#pic_center)

资源较为敏感,未展示全面,需要的最下面获取

![在这里插入图片描述](https://img-blog.csdnimg.cn/e4f9ac066e8c485f8407a99619f9c5b5.png#pic_center)![在这里插入图片描述](https://img-blog.csdnimg.cn/111f5462e7df433b981dc2430bb9ad39.png#pic_center)


##### ② 简历模板


![在这里插入图片描述](https://img-blog.csdnimg.cn/504b8be96bfa4dfb8befc2af49aabfa2.png#pic_center)

 **因篇幅有限,资料较为敏感仅展示部分资料,添加上方即可获取👆**

  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值