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

扩展说明

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值