# Rust Actix Web 入门指南

Rust Actix Web 入门指南

作者:Joshua Mo
日期:2023年12月15日

概述

  • Actix Web 入门
  • Actix Web 路由
  • 添加数据库
  • Actix Web 应用状态
  • 中间件
  • 静态文件服务
  • 部署
  • 总结

时至今日,Actix Web 仍然是 Rust Web 后端生态系统中极其强大的竞争者。尽管经历了一些事件,它依然保持强劲,成为 Rust 中最受推荐的 Web 框架之一。最初基于同名的 actor 框架(actix),现在已经脱离了原来的设计,现在 actix 主要用于 WebSocket 端点。

本文主要讨论 v4.4 版本。

Actix Web 入门

首先,使用 cargo init example-api 生成项目,然后进入项目目录,使用以下命令添加 actix-web 依赖:

cargo add actix-web

以下是基础的样板代码:

use actix_web::{
   
   web, App, HttpServer, Responder};

#[get("/")]
async fn index() -> impl Responder {
   
   
    "Hello world!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
   
   
    HttpServer::new(|| {
   
   
        App::new().service(
            web::scope("/")
                .route("/", web::get().to(index)),
        )
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

Actix Web 路由

在 Actix Web 中,任何返回 actix_web::Responder 特征的函数都可以作为路由。下面是一个基本的 Hello World 示例:

#[get("/")]
async fn index() -> impl Responder {
   
   
    "Hello world!"
}

对于更复杂的路由配置,可以使用 ServiceConfig

use actix_web::{
   
   web, App, HttpResponse};

fn config(cfg
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老大白菜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值