Actix Web 项目教程

Actix Web 项目教程

actix-websiteThe Actix Web website.项目地址:https://gitcode.com/gh_mirrors/ac/actix-website

1. 项目的目录结构及介绍

Actix Web 项目的目录结构通常包含以下几个主要部分:

actix-website/
├── src/
│   ├── main.rs
│   ├── lib.rs
│   ├── routes/
│   ├── services/
│   ├── models/
│   └── utils/
├── config/
│   ├── config.toml
│   └── settings.yaml
├── templates/
│   ├── index.html
│   └── layout.html
├── static/
│   ├── css/
│   ├── js/
│   └── images/
├── Cargo.toml
└── README.md

目录介绍

  • src/: 包含项目的源代码文件。
    • main.rs: 项目的入口文件。
    • lib.rs: 项目库文件(如果项目是一个库)。
    • routes/: 包含路由定义文件。
    • services/: 包含服务层代码文件。
    • models/: 包含数据模型定义文件。
    • utils/: 包含工具函数和辅助代码文件。
  • config/: 包含项目的配置文件。
    • config.toml: TOML 格式的配置文件。
    • settings.yaml: YAML 格式的配置文件。
  • templates/: 包含 HTML 模板文件。
    • index.html: 主页模板。
    • layout.html: 布局模板。
  • static/: 包含静态资源文件。
    • css/: 包含 CSS 文件。
    • js/: 包含 JavaScript 文件。
    • images/: 包含图片文件。
  • Cargo.toml: Rust 项目的依赖和元数据配置文件。
  • README.md: 项目说明文档。

2. 项目的启动文件介绍

项目的启动文件通常是 src/main.rs,它负责启动 HTTP 服务器并加载其他模块和配置。

// src/main.rs

use actix_web::{web, App, HttpServer};
use std::io;

#[actix_web::main]
async fn main() -> io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(web::resource("/").to(|| async { "Hello, World!" }))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

启动文件介绍

  • use actix_web::{web, App, HttpServer};: 导入 Actix Web 的相关模块。
  • #[actix_web::main]: 使用 Actix Web 的主函数宏。
  • async fn main() -> io::Result<()>: 定义异步主函数。
  • HttpServer::new(|| { ... }): 创建 HTTP 服务器实例。
  • App::new(): 创建应用实例。
  • .service(web::resource("/").to(|| async { "Hello, World!" })): 定义路由和处理函数。
  • .bind("127.0.0.1:8080")?: 绑定服务器到指定地址和端口。
  • .run().await: 启动服务器并等待请求。

3. 项目的配置文件介绍

项目的配置文件通常位于 config/ 目录下,常见的配置文件格式包括 TOML 和 YAML。

config.toml

# config/config.toml

[server]
host = "127.0.0.1"
port = 8080

[database]
url = "postgres://user:password@localhost/dbname"

settings.yaml

# config/settings.yaml

server:
  host: "127.0.0.1"
  port: 8080

database:
  url: "postgres://user:password@localhost/dbname"

配置文件介绍

  • [server]: 服务器配置部分。
    • host: 服务器监听的地址。
    • port: 服务器监听的端口。
  • [database]: 数据库配置部分。
    • **

actix-websiteThe Actix Web website.项目地址:https://gitcode.com/gh_mirrors/ac/actix-website

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

咎丹娜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值