繁体   English   中英

迁移到 actix-web 3.0 时出错

[英]Errors when moving to actix-web 3.0

迟到总比没有好,所以我开始重新学习 Rust 并决定专注于 actix 和 actix-web。

我有这些代码在 actix-web 1.0 中运行,但似乎没有在 actix-web 3.0 中运行:

main.rs

 use messages_actix::MessageApp;


 fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=info");
    env_logger::init();
    let app = MessageApp::new(8081);
    app.run() // error here
}

错误:“在impl std::future::Future impl std::future::Future找不到名为run的方法

库文件

#[macro_use]
extern crate actix_web;

use actix_web::{middleware, web, App, HttpRequest, HttpServer, Result};
use serde::Serialize;

pub struct MessageApp {
    pub port: u16,
}

#[derive(Serialize)]
pub struct IndexResponse{
    pub message: String,
}

#[get("/")]
pub fn index(req: HttpRequest) -> Result<web::Json<IndexResponse>> {  // error here
    let hello = req
        .headers()
        .get("hello")
        .and_then(|v| v.to_str().ok())
        .unwrap_or_else(|| "world");
    
        Ok(web::Json(IndexResponse {
            message: hello.to_owned(),
        }))
}

索引错误:特征Factory<_, _, _>未实现fn(HttpRequest) -> std::result::Result<Json<IndexResponse>, actix_web::Error> {<index as HttpServiceFactory>::register::index}

impl MessageApp {
    pub fn new(port: u16) -> Self {
        MessageApp{ port }
    }

    pub fn run(&self) -> std::io::Result<()> {
        println!("Starting HTTP server at 127.0.0.1:{}", self.port);
        HttpServer::new(move || {
            App::new()
            .wrap(middleware::Logger::default())
            .service(index)
        })
        .bind(("127.0.0.1", self.port))?
        .workers(8)
        .run() //error here
    }
}

错误:预期枚举std::result::Result ,找到 struct Server

检查了迁移文档,但找不到与列出的错误相关的内容。

非常感谢任何帮助...谢谢...

较新版本的actix-web现在使用async-await语法,从 Rust 1.39 开始稳定。 你必须让你的处理程序async

#[get("/")]
pub async fn index(req: HttpRequest) -> Result<web::Json<IndexResponse>> {
    // ...
}

创建一个HttpServer现在是一个async操作:

impl MessageApp {
    pub fn run(&self) -> std::io::Result<()>
        HttpServer::new(...)
          .run()
          .await
    }
}

您可以使用main宏在主 function 中使用 async/await:

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let app = MessageApp::new(8081);
    app.run().await
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM