当前位置: 首页 > 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!"}

扩展说明

相关文章:

  • Proxmox Mail Gateway安装指南:从零开始配置高效邮件过滤系统
  • DIY|Mac 搭建 ESP-IDF 开发环境及编译小智 AI
  • Pycharm中添加不了新建的Conda环境(此篇专门给Daidai写的)
  • 衡量嵌入向量的相似性的方法
  • 服务器磁盘空间被Docker容器日志占满处理方法
  • 青少年编程与数学 01-011 系统软件简介 05 macOS操作系统
  • 基于IDIG-GAN的小样本电机轴承故障诊断
  • Mac下Android Studio扫描根目录卡死问题记录
  • WebRTC 与 WebSocket 的关联关系
  • 代码安全规范1.1
  • QuaggaJS用法详解
  • elasticsearch基本操作笔记
  • Ubuntu 基于sdl 音频学习的基础代码
  • WebRTC源码线程-1
  • 天机学堂(学习计划和进度)
  • react public/index.html文件使用env里面的变量
  • 〈软件安装管家软件目录〉▷Windows系统版
  • 基于cornerstone3D的dicom影像浏览器 第二十九章 自定义菜单组件
  • 安装VUE客户端@vue/cli报错警告npm WARN deprecated解决方法 无法将“vue”项识别为 cmdlet、函数
  • 机器学习框架PyTorch
  • 佛山专业的网站建设公司/百度网络营销中心app
  • 监控做直播网站/cfa三级和一二级关系大吗
  • 住房公积金网站怎么做减员/产品营销
  • 做家纺的主要国际网站/seo描述快速排名
  • 电子商务的网站建设过程/免费发软文的网站
  • html5网站案例/seo推广服务哪家好