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

扩展说明

相关推荐
IT_陈寒13 分钟前
JavaScript实战技巧总结:深挖数组遍历的性能陷阱与实战解法
前端·人工智能·后端
步行cgn21 分钟前
为什么既要 web.xml 又要 springmvc.xml?能不能只配一个?
xml·前端·hive
风骏时光牛马28 分钟前
大模型综合能力评测:多维度性能与对齐效果对比
前端
winfredzhang33 分钟前
从零手写一个毛玻璃风格的页面搭建台:单文件 HTML 实现组件放置、面板磁吸与图层管理
前端·html
葡萄城技术团队9 小时前
1000 人协同压测的环境瓶颈排查:CPU 争用与 Wi\-Fi
前端
excel10 小时前
Marked 与 Markdown 有什么区别?该怎么选?
前端
Da Da 泓11 小时前
五子棋 Web 端测试用例报告
前端·网络·websocket·网络协议·测试用例·项目
zxcvb15312 小时前
远程查看本地文档:一条轻量 Web 文件服务的工程化链路
前端·远程查看文档
niucloud-admin12 小时前
NIUCLOUD PHP SAAS上门家政使用文档:城市管理
java·前端·php
北岛贰12 小时前
啵啵音乐迎来全新升级!
前端