六、用 Actix-web 构建异步 web工程

tech2022-07-09  177

六、用 Actix-web 构建异步 web工程      目前 Rust 的 web 框架已经有挺多了,考虑到可靠性,异步化,结构化,流行速度,使用简单,等多方面因素后,这里笔者最终选择了 actix-web。本节一起来看下 actix-web 的使用情况。      用 CLion 打开之前的工程。首先,来看一下项目结构:

. ├── Cargo.toml ├── README.md └── src ├── main.rs └── module ├── mod.rs └── user ├── api.rs ├── mod.rs └── model.rs

    接下来,我们将其改造为一个异步 web 工程。

1、Cargo.toml

[dependencies] actix-web = "3.0.1" serde = "1.0.114" validator = "0.10.1" validator_derive = "0.10.1"

2、module/user/model.rs

use serde::{Deserialize, Serialize}; use validator::Validate; #[derive(Debug, Validate, Serialize, Deserialize)] pub struct User { pub id: Option<i64>, #[validate(length(max = 50, message = "username must be less than 50 chars."))] pub username: String, #[validate(length(min = 6, message = "password must be more than 6 chars."))] pub password: String, #[validate(length(max = 255, message = "username must be less than 255 chars."))] pub avatar: Option<String>, #[validate(length(max = 80, message = "username must be less than 80 chars."))] pub email: Option<String>, }

3、module/user/api.rs

use actix_web::{delete, get, HttpResponse, post, put, Responder, web}; use actix_web::web::Json; use crate::module::user::model::User; /** * 测试接口: 增 */ #[post("/user")] pub async fn create(user: Json<User>) -> impl Responder { HttpResponse::Ok().json(user.0) } /** * 测试接口: 查 */ #[get("/user/{id}}")] pub async fn show(web::Path(id): web::Path<i64>) -> impl Responder { HttpResponse::Ok().json(id) } /** * 测试接口: 改 */ #[put("/user/{id}")] pub async fn update(web::Path(id): web::Path<i64>, user: Json<User>) -> impl Responder { let mut user = user.into_inner(); user.id = Some(id); HttpResponse::Ok().json(user) } /** * 测试接口: 删 */ #[delete("/user/{id}")] pub async fn delete(web::Path(id): web::Path<i64>) -> impl Responder { HttpResponse::Ok().json(id) }

4、module/user/mod.rs

pub mod api; //pub mod bs; //pub mod dao; pub mod model;

5、module/mod.rs

pub mod user; pub mod handler { use actix_web::dev::HttpServiceFactory; use actix_web::web; use crate::module::user; pub fn api_routes() -> impl HttpServiceFactory { web::scope("") .service(user::api::create) .service(user::api::show) .service(user::api::update) .service(user::api::delete) } }

6、src/main.rs

#[macro_use] extern crate validator_derive; use actix_web::{App, HttpServer}; mod module; #[actix_web::main] async fn main() -> std::io::Result<()> { HttpServer::new(move || App::new() .service(module::handler::api_routes()) ).bind("0.0.0.0:8080")?.run().await }

   在项目的根目录执行:cargo run。

Finished dev [unoptimized + debuginfo] target(s) in 0.18s Running `target/debug/rust-demo`

   看到上面信息后,就可以使用 post + json,尝试请求了。

curl -H "Content-Type: application/json" -X POST -d \ '{"email": "xugy3@126.com", "username": "xugy4", "password": "123456", "avatar": "https://avatars3.githubusercontent.com/u/13329376?s=460&v=4"}' http://127.0.0.1:8080/user

    本节进行了一个异步 web 工程的简单探索,读者可以多尝试一下本节 demo,比如打印一下参数对象等。同时,本 demo 也将是后续更多工作的基础。OK,这次就到这里 !!

 

最新回复(0)