Actix Web 入门

目标

完成提交表单至后端,然后接受返回数据

捕获.PNG

捕获.PNG

Hello,world!

actix-web 是采用 Rust 开发的一个 Web 框架。它强大快速切于实际,是采用 Rust 进行 Web 开发的最佳选择之一——那还学学?

依照惯例,选择创建一个 hello_world 程序来初步了解下 actix-web。

首先使用 Cargo 创建一个名为 hello_world 新项目。

cargo new hello_world
cd hello_world
复制代码

接着,在 hello_world 目录下的 Cargo.toml 中添加:

[dependencies]
actix-web = "3"
复制代码

将 actix-web 添加为项目的依赖项。

我们逐步分析 Hello,world! 的代码

use actix_web::{get, App, HttpResponse, HttpServer, Responder};

//路由指定路径(以 get 的方式)
#[get("/")]
async fn hello() -> impl Responder {
    //返回报文主体为 Hello,world 的 Http 响应
    HttpResponse::Ok().body("Hello,world!")
}

//将 async main 函数标记为 actix 系统的入口点。 
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    //创建 http 服务器
    HttpServer::new(|| {
        App::new()//新建一个应用
            .service(hello)//将 hello 函数作为服务
    })
    .bind("127.0.0.1:8080")?//绑定到指定的套接字地址
    .run()//开始监听
    .await
}
复制代码

在 hello_world 目录下运行命令:cargo run,启动服务。

然后启动浏览器输入我们指定的套接字地址:127.0.0.1:8080

捕获.PNG

FromRequest trait

当我们向一个地址发送请求时,往往都会伴随着一些其他信息,而 FromRequest trait 规定了一些格式,共我们去提取请求信息。

最为简单的是请求主体是段文本需要被接收:

use actix_web::{post, App, HttpResponse, HttpServer, Responder};

//路由 /post 的请求 
#[post("/post")]
async fn get_text(txt: String) -> impl Responder {
    HttpResponse::Ok().body(format!("成功接收到了:{}", txt))
}

//将 async main 函数标记为 actix 系统的入口点。
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    //创建 http 服务器
    HttpServer::new(|| {
        App::new() //新建一个应用
            .service(get_text)
    })
    .bind("127.0.0.1:8080")? //绑定到指定的套接字地址
    .run() //开始监听
    .await
}
复制代码

其它的格式可以查看 Trait actix_web::FromRequest

提交表单

构建页面

首先用 Html 构建一个基本的具有提交表单功能的页面。我们新建项目 form ,然后在 form 目录下新建文件夹 pages 并在里面新建文件 index.html。

捕获.PNG

添加依赖项:

[dependencies]
actix-web = "3"
serde = { version = "1", features = ["derive"] }
复制代码

编写 Html :

<!DOCTYPE html>
<html>

<body>
    <h3>请问你是?</h3>
    <form action=/post method=POST>
        <button type=submit>我是:</button>
        <input name="name">
    </form>
</body>

</html>
复制代码

很标准的提交表单:

捕获.PNG

接着我们逐步分析 Rust 代码:

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use serde::{Deserialize, Serialize};

//表单格式,对应 Html 中的 name
#[derive(Serialize, Deserialize)]
pub struct Person {
    name: String,
}

//显示初始(pages/index.html)页面
async fn index() -> HttpResponse {
    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")//格式
        .body(include_str!("../pages/index.html"))//读取文件作为相应主体
}

async fn post(p: web::Form<Person>) -> impl Responder {
    HttpResponse::Ok()
        .content_type("text/html; charset=utf-8")//防止乱码
        .body(format!("欢迎 {}", p.name))//读取表单内容
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            //以另一种方式实现 get 和 post 请求
            .service(web::resource("/").route(web::get().to(index)))//路由根目录
            .service(web::resource("/post").route(web::post().to(post)))//路由 /post 目录
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
复制代码

接着运行,并提交:

捕获.PNG

捕获.PNG

欢迎大家评论交流!

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享