当前位置: 首页 > news >正文

基于 actix-web 框架的简单 demo

以下是一个基于 actix-web 框架的简单 demo,

如果你还没有 Rust,我们建议你使用 rustup 来管理你的 Rust 安装。官方 Rust 指南有一个很棒的入门部分。

Actix Web 目前支持的最低 Rust 版本 (MSRV) 为 1.72。运行 rustup update 将确保您拥有最新最好的 Rust 版本。因此,本指南假定您运行的是 Rust 1.72 或更高版本。

包含一个基本的路由和 JSON 响应功能。

基于 actix-web 框架的简单 demo

依赖配置

Cargo.toml 中添加以下依赖:

[dependencies]
actix-web = "4"
serde = { version = "1", features = ["derive"] }

示例代码

创建一个简单的 HTTP 服务器,包含 //greet/{name} 路由:

代码1
use actix_web::{get, App, HttpServer, Responder, web};
use serde::Serialize;#[derive(Serialize)]
struct Greeting {message: String,
}#[get("/")]
async fn hello() -> impl Responder {"Hello, Actix Web!"
}#[get("/greet/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {web::Json(Greeting {message: format!("Hello, {}!", name),})
}#[actix_web::main]
async fn main() -> std::io::Result<()> {HttpServer::new(|| {App::new().service(hello).service(greet)}).bind("127.0.0.1:8080")?.run().await
}
代码2
use actix_web::{get, web, App, HttpServer, Responder};#[get("/hello/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {format!("Hello {}!", name)
}#[actix_web::main] // or #[tokio::main]
async fn main() -> std::io::Result<()> {HttpServer::new(|| {App::new().service(greet)}).bind(("127.0.0.1", 8080))?.run().await
}
代码3
use actix_web::{get, web, App, HttpServer, Responder};#[get("/")]
async fn index() -> impl Responder {"Hello, World!"
}#[get("/{name}")]
async fn hello(name: web::Path<String>) -> impl Responder {format!("Hello {}!", &name)
}#[actix_web::main]
async fn main() -> std::io::Result<()> {HttpServer::new(|| App::new().service(index).service(hello)).bind(("127.0.0.1", 8080))?.run().await
}

运行方式

在项目目录下执行:

cargo run

测试接口

  • 访问 http://127.0.0.1:8080/,返回纯文本 Hello, Actix Web!
  • 访问 http://127.0.0.1:8080/greet/Alice,返回 JSON:
{"message": "Hello, Alice!"}

扩展说明

http://www.lqws.cn/news/173881.html

相关文章:

  • 前端项目初始化
  • ant-design4.xx实现数字输入框; 某些输入法数字需要连续输入两次才显示
  • 前端关于position: sticky
  • 大数据量高实时性场景下订单生成的优化方案
  • NoSQL 之Redis哨兵
  • HarmonyOS运动开发:如何用mpchart绘制运动配速图表
  • Imprompter: Tricking LLM Agents into Improper Tool Use
  • 佰力博科技与您探讨材料介电性能测试的影响因素
  • 使用vsftpd搭建FTP服务器(TLS/SSL显式加密)
  • 手机如何防止ip关联?3种低成本方案
  • CRMEB 框架中 PHP 上传扩展开发:涵盖本地上传及阿里云 OSS、腾讯云 COS、七牛云
  • 数学:数的概念是如何发展的?
  • Python训练营打卡 Day46
  • 现代Web安全实践:基于Token与Refresh Token的单点登录(SSO)实现
  • C++11 右值引用:从入门到精通
  • 博弈论概述
  • 深入解析Java中的装箱与拆箱机制
  • Mysql中select查询语句的执行过程
  • SpringBoot 自动化部署实战:CI/CD 整合方案与避坑指南
  • 深克隆java对象的方式
  • 基于 Vue 和 Spring Boot 实现滑块验证码的机器验证
  • 【Linux】awk 命令详解及使用示例:结构化文本数据处理工具
  • python训练营打卡第46天
  • 打造你的 Android 图像编辑器:深入解析 PhotoEditor 开源库
  • windows server 添加自动启动服务
  • 使用阿里云百炼embeddings+langchain+Milvus实现简单RAG
  • PostgreSQL17 编译安装+相关问题解决
  • KAG与RAG在医疗人工智能系统中的多维对比分析
  • 完美搭建appium自动化环境
  • PyQt常用控件的使用:QFileDialog、QMessageBox、QTreeWidget、QRadioButton等