rust actixweb框架学习

2025-05-20

actix-web框架的学习

又是无聊的一天, rust我想好好学学,虽然基础也不咋地 但是想学个框架尝尝鲜,听说这个actix-web框架是性能高,而且支持异步,听起来挺酷的,学学试试

相关的链接推荐:

rust actix-web中文文档 还有一个教程视频: 软件工艺师大佬的教程

我没看完,(恼),先随便写写吧

介绍

一个开源的高性能的web框架,听说是高性能,我也就用来尝尝鲜,入入门(喜)

基础入门

先编写一个简单的事例看看,需要先添加该库

cargo add actix-web

我一般喜欢用命令来添加,也方便

一个大致页面如下:

use actix-web::{App,get,post,Responseder,HttpResonse,HttpServer};

//rust的handlers支持使用宏来进行一些路由信息配置,还有别的方法,后续再聊

#[get("/index")]
async fn index()->impl Responseder{
    HttpResponse::Ok().body("indexpage")
}
async fn helloworld()->impl Responseder{
    HttpResponse::Ok().body("hello actix-web")
}


//用宏实现默认为main实现异步
#[actix_web::main]
async fn main()->std::io::Result<()>{
    //基本一个server启动流程
    let server=HttpServer::new(||{
        //service代表服务
        App::new().service(index).service(helloworld)
        //bind绑定地址
    }).bind("127.0.0.1:8080")?.run().await;
  
}

大致就这样

编写应用

作用域

scope(作用域)差不多是做为一个路由的命名空间

比如,应用程序的作用域为 /app,即路径前缀为 /app。那么,路径为 /app、/app/,或者 /app/test 的请求都可以匹配;但是,路径 /application 不能匹配

状态

应用程序状态,被同一作用域内所有路由和资源共享 web::Data<T> 访问状态(state)实现,这个web::Data<T>连接数据库的时候可以用的到

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

// This struct represents state
struct AppState {
    app_name: String,
}

#[get("/")]
async fn index(data: web::Data<AppState>) -> String {
    let app_name = &data.app_name; // <- get app_name

    format!("Hello {}!", app_name) // <- response with app_name
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .data(AppState {
                app_name: String::from("Actix-web"),
            })
            .service(index)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

共享可变状态

之后在接着写….