微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从函数返回actix web App实例?

如何解决如何从函数返回actix web App实例?

我想将创建的应用实例传递给 HttpServer,像这样 HttpServer::new(app::init()),它不起作用。

app.rs

use crate::db::new_pool;
use crate::message_handler::MessageHandler;
use crate::route;
use actix::prelude::{Addr,SyncArbiter};
use actix_web::{
    middleware::Logger,App,http::header::{AUTHORIZATION,CONTENT_TYPE},};

use actix_cors::Cors;
use std::env;

pub struct AppState {
    pub message_handler: Addr<MessageHandler>,}

pub fn init<T,B>() -> App<T,B> {
    let frontend_origin = env::var("FRONTEND_ORIGIN").ok();

    let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
    let database_pool = new_pool(database_url).expect("Failed to create pool.");

    let message_handler = SyncArbiter::start(num_cpus::get(),move || MessageHandler {
        db_connection_pool: database_pool.clone()
    });

    let bind_address = env::var("BIND_ADDRESS").expect("BIND_ADDRESS is not set");

    let state = AppState {
        message_handler: message_handler.clone(),};
    // let cors = match frontend_origin {
    //     Some(ref origin) => Cors::default()
    //         .allowed_origin(origin)
    //         .allowed_headers(vec![AUTHORIZATION,CONTENT_TYPE])
    //         .max_age(3600),//     None => Cors::default()
    //         .allowed_origin("*")
    //         .send_wildcard()
    //         .allowed_headers(vec![AUTHORIZATION,// };
    App::new()
        .data(state)
        .wrap(Logger::default())
        // .wrap(cors)
        .configure(route::routes)
}

main.rs

use env_logger;
use std::env;
use actix_web_tutorial::app;
use actix_web::HttpServer;

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    dotenv::dotenv().ok();

    if env::var("RUST_LOG").ok().is_none() {
        env::set_var("RUST_LOG","info");
    }
    env_logger::init();

    let bind_address = env::var("BIND_ADDRESS").expect("BIND_ADDRESS is not set");

    HttpServer::new(app::init())
    .bind(&bind_address)
    .unwrap_or_else(|_| panic!("Could not bind server to address {}",&bind_address))
    .run()
    .await
}

相关问题:

  1. rust actix: how can I properly return an App instance from a module?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。