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