如何在 Actix-Web 中返回已配置的应用程序?

rea*_*jin 4 rust actix-web

我正在使用 actix-web 创建一个嵌入状态/数据的 httpserver。但 vscode 告诉我该create_app函数的返回值类型定义中有错误的参数App<AppState>

pub struct App<T, B>
wrong number of type arguments: expected 2, found 1
expected 2 type argumentsrustc(E0107)
Run Code Online (Sandbox Code Playgroud)

应用程序.rs:

use crate::api;
use crate::model::DbExecutor;
use actix::prelude::Addr;
use actix_web::{error, http::Method, middleware::Logger, web, App, HttpResponse};

pub struct AppState {
    pub db: Addr<DbExecutor>,
}

pub fn create_app(db: Addr<DbExecutor>) -> App<AppState> {
    App::new().data(AppState { db }).service(
        web::resource("/notes/").route(web::get().to(api::notes))
    );
}
Run Code Online (Sandbox Code Playgroud)

主要.rs:

fn main() {
    HttpServer::new(move || app::create_app(addr.clone()))
        .bind("127.0.0.1:3000")
        .expect("Can not bind to '127.0.0.1:3000'")
        .start();
}
Run Code Online (Sandbox Code Playgroud)

由于“service”方法的返回类型是“Self”,类型为 actix_web::App,我尝试将返回类型修改为 App(不带泛型参数),但仍然出现错误,我该怎么办?

arv*_*ve0 9

首先,App采用两个泛型类型参数,App<AppEntry, Body>您只给出了一个。

第二,AppState不是AppEntry

第三,App在 actix-web 外部实例化即使不是不可能,也是很困难的,因为您需要的 actix-web 类型不是公开的。

相反,您应该使用配置来实现相同的目的,这是一个简化的示例:

use actix_web::web::{Data, ServiceConfig};
use actix_web::{web, App, HttpResponse, HttpServer};

fn main() {
    let db = String::from("simplified example");

    HttpServer::new(move || App::new().configure(config_app(db.clone())))
        .bind("127.0.0.1:3000")
        .expect("Can not bind to '127.0.0.1:3000'")
        .run()
        .unwrap();
}

fn config_app(db: String) -> Box<dyn Fn(&mut ServiceConfig)> {
    Box::new(move |cfg: &mut ServiceConfig| {
        cfg.app_data(db.clone())
            .service(web::resource("/notes").route(web::get().to(notes)));
    })
}

fn notes(db: Data<String>) -> HttpResponse {
    HttpResponse::Ok().body(["notes from ", &db].concat())
}
Run Code Online (Sandbox Code Playgroud)

请阅读api 文档ServiceConfig了解更多信息。

  • @inzanez 更新了答案,解释为什么返回 `App&lt;AppState&gt;` 是错误的,并回答“我应该做什么?” (2认同)