基于 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
Go 复制代码
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!"}

扩展说明

相关推荐
集成显卡3 分钟前
PlayWright | 初识微软出品的 WEB 应用自动化测试框架
前端·chrome·测试工具·microsoft·自动化·edge浏览器
前端小趴菜051 小时前
React - 组件通信
前端·react.js·前端框架
Amy_cx1 小时前
在表单输入框按回车页面刷新的问题
前端·elementui
dancing9991 小时前
cocos3.X的oops框架oops-plugin-excel-to-json改进兼容多表单导出功能
前端·javascript·typescript·游戏程序
后海 0_o2 小时前
2025前端微服务 - 无界 的实战应用
前端·微服务·架构
Scabbards_2 小时前
CPT304-2425-S2-Software Engineering II
前端
小满zs2 小时前
Zustand 第二章(状态处理)
前端·react.js
程序猿小D2 小时前
第16节 Node.js 文件系统
linux·服务器·前端·node.js·编辑器·vim
萌萌哒草头将军2 小时前
🚀🚀🚀Prisma 发布无 Rust 引擎预览版,安装和使用更轻量;支持任何 ORM 连接引擎;支持自动备份...
前端·javascript·vue.js
狼性书生2 小时前
uniapp实现的简约美观的星级评分组件
前端·uni-app·vue·组件