Rust Web开发框架actix-web入门案例

news/2024/9/20 7:36:41/ 标签: rust, 前端, 开发语言

概述

在看书的时候,用到了actix-web这个框架的案例。

书里面的版本是1.0,但是我看官网最新都4.4了。

为了抹平这种信息差,所以我决定把官方提供的示例代码过一遍。

核心代码

Cargo.toml

[package]
name = "hello"
version = "0.1.0"
edition = "2021"[dependencies]
actix-web = "4.4"
env_logger = "0.11"
log = "0.4"

main.rs

rust">use actix_web::{middleware, web, App, HttpRequest, HttpServer};async fn index(req: HttpRequest) -> &'static str {println!("REQ: {req:?}");"Hello world!"
}#[actix_web::main]
async fn main() -> std::io::Result<()> {env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));log::info!("starting HTTP server at http://192.168.77.129:8000");let server = HttpServer::new(|| {App::new().wrap(middleware::Logger::default()).service(web::resource("/index.html").to(|| async {"Hello html!"})).service(web::resource("/").to(index))});server.bind("0.0.0.0:8000")?.run().await
}

运行和访问

http://192.168.77.129:8000/
在这里插入图片描述

http://192.168.77.129:8000/index.html
在这里插入图片描述

代码解读

引入依赖:

rust">use actix_web::{middleware, web, App, HttpRequest, HttpServer};

首页路由:

  • 获取请求信息:index(req: HttpRequest)
  • 返回一个纯文本字符串:&'static str
rust">async fn index(req: HttpRequest) -> &'static str {println!("REQ: {req:?}");"Hello world!"
}

入口方法:

  • 定义入口方法:#[actix_web::main]
  • 声明入口方法:async fn main() -> std::io::Result<()> {
  • 初始化日志:env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
  • 记录一个info级别的日志:log::info!("starting HTTP server at http://192.168.77.129:8000");
  • 创建服务对象:let server = HttpServer::new(|| {
  • 使用日志中间件:.wrap(middleware::Logger::default())
  • 挂载路由/index.html.service(web::resource("/index.html").to(|| async {"Hello html!"}))
  • 挂载路由/ .service(web::resource("/").to(index))
  • 启动服务:server.bind("0.0.0.0:8000")?
rust">#[actix_web::main]
async fn main() -> std::io::Result<()> {env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));log::info!("starting HTTP server at http://192.168.77.129:8000");let server = HttpServer::new(|| {App::new().wrap(middleware::Logger::default()).service(web::resource("/index.html").to(|| async {"Hello html!"})).service(web::resource("/").to(index))});server.bind("0.0.0.0:8000")?.run().await
}

测试代码

actix-web框架还支持对web进行测试。

核心代码如下:

  • 创建应用对象:let app = App::new().route("/", web::get().to(index));
  • 设置测试对象:let app = test::init_service(app).await;
  • 构造请求对象:let req = test::TestRequest::get().uri("/").to_request();
  • 发送请求,获取响应:let resp = app.call(req).await?;
  • 断言响应状态码:assert_eq!(resp.status(), http::StatusCode::OK);
  • 获取响应体内容:let response_body = resp.into_body();
  • 断言响应体内容:assert_eq!(to_bytes(response_body).await?, r##"Hello world!"##);
rust">#[cfg(test)]
mod tests {use actix_web::{body::to_bytes, dev::Service, http, test, Error};use super::*;#[actix_web::test]async fn test_index() -> Result<(), Error> {let app = App::new().route("/", web::get().to(index));let app = test::init_service(app).await;let req = test::TestRequest::get().uri("/").to_request();let resp = app.call(req).await?;assert_eq!(resp.status(), http::StatusCode::OK);let response_body = resp.into_body();assert_eq!(to_bytes(response_body).await?, r##"Hello world!"##);Ok(())}
}

完整代码:

rust">use actix_web::{middleware, web, App, HttpRequest, HttpServer};async fn index(req: HttpRequest) -> &'static str {println!("REQ: {req:?}");"Hello world!"
}#[actix_web::main]
async fn main() -> std::io::Result<()> {env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));log::info!("starting HTTP server at http://192.168.77.129:8000");let server = HttpServer::new(|| {App::new().wrap(middleware::Logger::default()).service(web::resource("/index.html").to(|| async {"Hello html!"})).service(web::resource("/").to(index))});server.bind("0.0.0.0:8000")?.run().await
}#[cfg(test)]
mod tests {use actix_web::{body::to_bytes, dev::Service, http, test, Error};use super::*;#[actix_web::test]async fn test_index() -> Result<(), Error> {let app = App::new().route("/", web::get().to(index));let app = test::init_service(app).await;let req = test::TestRequest::get().uri("/").to_request();let resp = app.call(req).await?;assert_eq!(resp.status(), http::StatusCode::OK);let response_body = resp.into_body();assert_eq!(to_bytes(response_body).await?, r##"Hello world!"##);Ok(())}
}

执行测试:

(base) zhangdapeng@zhangdapeng:~/code/rust/hello$ cargo test
warning: `/home/zhangdapeng/.cargo/config` is deprecated in favor of `config.toml`
note: if you need to support cargo 1.38 or earlier, you can symlink `config` to `config.toml`
warning: `/home/zhangdapeng/.cargo/config` is deprecated in favor of `config.toml`
note: if you need to support cargo 1.38 or earlier, you can symlink `config` to `config.toml`Finished `test` profile [unoptimized + debuginfo] target(s) in 0.14sRunning unittests src/main.rs (target/debug/deps/hello-4420b7c0e788b52b)running 1 test
test tests::test_index ... oktest result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

http://www.ppmy.cn/news/1462010.html

相关文章

GPT-4o“成精了”:推测技术原理,附送“美国湾区”小道消息

原创&#xff1a;谭婧 如果你能跟上技术发展&#xff0c;那大多数技术提升都是按部就班&#xff0c; 偶而会有突破性进展。 如果你仅仅吃瓜&#xff0c;那OpenAI的所有新闻&#xff0c; 你都可以写成&#xff1a; “改写历史”“干翻所有”“颠覆世界”。 真的颠覆世界了吗&…

Hello, GPT-4o!

2024年5月13日&#xff0c;OpenAI 在官网正式发布了最新的旗舰模型 GPT-4o 它是一个 多模态模型&#xff0c;可以实时推理音频、视频和文本。 * 发布会完整版视频回顾&#xff1a;https://www.youtube.com/watch?vDQacCB9tDaw GPT-4o&#xff08;“o”代表“omni”&#xff0c…

【会议征稿】2024年机器人前沿技术与创新国际会议(FTIR 2024, 7/19-21)

2024年机器人前沿技术与创新国际会议&#xff08;FTIR 2024&#xff09;将于2024年7月19-21日在中国杭州举行。FTIR 2024聚焦前沿技术与创新&#xff0c;将把机器人领域的创新学者和专家聚集到一个共同的论坛。会议的主要目标是促进机器人的研究和开发活动&#xff0c;另一个目…

Qt三方库:QuaZIP介绍、编译和使用

前言 Qt使用一些压缩解压功能&#xff0c;探讨过libzip库&#xff0c;zlib库&#xff0c;libzip库比较原始&#xff0c;还有其他库&#xff0c;都比较基础&#xff0c;而在基础库之上&#xff0c;又有高级封装库&#xff0c;Qt中的QuaZIP是一个很好的选择。Quazip是一个用于压缩…

yolov9训练自定义数据

1.训练yolov9&#xff0c;先准备好一份自定义数据.。到roboflow下载一份数据&#xff0c;数据格式是yolo格式。 2.到github下载yolov9源码 https://github.com/WongKinYiu/yolov9 3.为了方便配置环境&#xff0c;把代码上传到矩池云上面&#xff0c;使用云服务器 4.执行 pip i…

【Bug】Clash出现端口0的情况

win版本的Docker桌面版用了Hyper-V的功能&#xff0c;虚拟机需要映射一部分端口&#xff0c;并且在系统更新后对动态映射的端口范围进行了更改&#xff0c;导致占用了本来的7890Clash使用的端口。 cmd去查看还能使用的端口 netsh interface ipv4 show excludedportrange prot…

ArcGI基本技巧-科研常用OLS, GWR, GTWR模型实现

ArcGI基本技巧-科研常用OLS, GWR, GTWR模型实现 OLS,GWR,GTWR回归模型均可以揭示解释变量对被解释变量的影响且可以进行预测。Ordinary Least Squares (OLS)是最小二乘法&#xff0c;Geographically Weighted Regression (GWR)是地理加权回归&#xff0c;Geographically and T…

openFeign 调用后 返回 出现 application/json 错误

项目场景&#xff1a; 远程调用时返回json格式错误 项目场景&#xff1a;从分页插件式改换为原生分页的时候 通过openFeign调用时发现了问题 问题描述 不需要openFeign 调用的时候 返回的数据和格式是对 通过openFeign 调用后返回 出现 application/json 错误 &#xff1a; …

代码随想录--链表--反转链表

题目 题意&#xff1a;反转一个单链表。 示例: 输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL 思路 如果再定义一个新的链表&#xff0c;实现链表元素的反转&#xff0c;其实这是对内存空间的浪费。 其实只需要改变链表的next指针的…

AI4Science

AI4Science 文章目录 AI4ScienceMicroSoft AI4Science其它 微软研究院刘铁岩&#xff1a;AI for Science&#xff0c;追求人类智能最光辉的一面&#xff5c;MEET2023 &#xff08;17min&#xff09; https://www.bilibili.com/video/BV1bs4y1W7rW/AI Forum 2023 | AI4Science: …

项目-坦克大战

增加功能 我方坦克在发射的子弹消亡后&#xff0c;才能发射新的子弹。同时实现发多颗子弹 1&#xff0c;在按下J键&#xff0c;我们判断当前hero对象的子弹&#xff0c;是否已经销毁2&#xff0c;如果没有销毁&#xff0c;就不去触发shotEnemyTank3&#xff0c;如果已经销毁&…

Android系统不同版本存储权限

一、Android存储简介 Android系统分为内部存储和外部存储 从Android6.0开始不断在更新存储&#xff08;读写&#xff09;权限&#xff0c;除了在AndroidManifest.xml文件里声明&#xff0c;app运行时也要动态申请使用对应的权限 提醒&#xff1a;应用私有存储不需要动态申请权…

AtCoder Beginner Contest 318 A题 Full Moon

A题&#xff1a;Full Moon 标签&#xff1a;模拟、数学题意&#xff1a;给定一个起始 m m m和上限 n n n&#xff0c;每次增量 p p p&#xff0c;求能加几次。题解&#xff1a;数据比较小&#xff0c;可以直接暴力&#xff1b;数学方法算的话&#xff0c;注意边界。代码&#…

2024数维杯数学建模C题思路代码

2024年数维杯&电工杯思路代码在线文档​https://www.kdocs.cn/l/cdlol5FlRAdE 这道题想要做出好的结果&#xff0c;必须要结合插值法和分布函数来做&#xff0c;主要还是因为勘探点太少&#xff0c;直接用插值法效果不太好&#xff0c;以下是我做的&#xff0c;函数分布可…

AMD W7900本地大型语言模型的微调

GenAI-contest/01-LLM_Fine-tuning at main amd/GenAI-contest (github.com) 大型语言模型&#xff08;LLMs&#xff09;在大量的文本数据上进行训练。因此&#xff0c;它们能够生成连贯且流畅的文本。Transformer架构是所有LLMs的基础构建块&#xff0c;它作为底层架构&…

快速掌握Spring底层原理整体脉络

快速掌握Spring底层原理整体脉络 介绍 在Java开发领域&#xff0c;Spring框架是一个非常流行的选择。作为一名Java架构师&#xff0c;了解Spring底层原理是非常重要的。本文将帮助你快速掌握Spring底层原理的整体脉络&#xff0c;让你更好地理解和应用Spring框架。 Spring框…

超级好用的C++实用库之MD5信息摘要算法

&#x1f4a1; 需要该C实用库源码的大佬们&#xff0c;可搜索微信公众号“希望睿智”。添加关注后&#xff0c;输入消息“超级好用的C实用库”&#xff0c;即可获得源码的下载链接。 概述 MD5信息摘要算法是一种广泛使用的密码散列函数&#xff0c;由Ronald L. Rivest在1991年设…

Python | Leetcode Python题解之第92题反转链表II

题目&#xff1a; 题解&#xff1a; class Solution:def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:# 设置 dummyNode 是这一类问题的一般做法dummy_node ListNode(-1)dummy_node.next headpre dummy_nodefor _ in range(left - 1):pre…

力扣HOT100 - 215. 数组中第K个最大元素

解题思路&#xff1a; 快速选择&#xff0c;目标是找出数组中第 k 小&#xff08;或第 k 大&#xff09;的元素&#xff0c;而不是对整个数组进行排序。 &#xff08;需要和快排进行区分&#xff0c;快排的目的是排序&#xff09; 注意&#xff1a; i l - 1, j r 1; 为什…

深度学习中常见的九种交叉验证方法汇总

目录 1. K折交叉验证&#xff08;K-fold cross-validation&#xff09; 2. 分层K折交叉验证&#xff08;Stratified K-fold cross-validation&#xff09; 3. 时间序列交叉验证&#xff08;Time Series Split&#xff09; 4. 留一交叉验证&#xff08;Leave-One-Out Cross-…