基于 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!"}

扩展说明

相关推荐
掘金安东尼11 分钟前
前端周刊第421期(2025年7月1日–7月6日)
前端·面试·github
摸鱼仙人~13 分钟前
深入理解 classnames:React 动态类名管理的最佳实践
前端·react.js·前端框架
未来之窗软件服务15 分钟前
chrome webdrive异常处理-session not created falled opening key——仙盟创梦IDE
前端·人工智能·chrome·仙盟创梦ide·东方仙盟·数据调式
kymjs张涛16 分钟前
零一开源|前沿技术周报 #6
前端·ios·harmonyos
玲小珑19 分钟前
Next.js 教程系列(十)getStaticPaths 与动态路由的静态生成
前端·next.js
天天鸭25 分钟前
写个vite插件自动处理系统权限,降低99%重复工作
前端·javascript·vite
蓝婷儿30 分钟前
每天一个前端小知识 Day 23 - PWA 渐进式 Web 应用开发
前端
无奈何杨39 分钟前
CoolGuard风控中新增移动距离和移动速度指标
前端·后端
恋猫de小郭1 小时前
Google I/O Extended :2025 Flutter 的现状与未来
android·前端·flutter
江城开朗的豌豆1 小时前
Vue-router方法大全:让页面跳转随心所欲!
前端·javascript·vue.js