首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在使用函数修饰时,如何将App数据传递到actix-web中的服务路由处理函数?

在使用函数修饰时,如何将App数据传递到actix-web中的服务路由处理函数?
EN

Stack Overflow用户
提问于 2019-10-18 00:07:46
回答 1查看 2.4K关注 0票数 2

我在文档中找到了一个如何创建全局状态的示例,该状态由互斥锁保护,并在处理线程之间共享,可供所有路由处理程序使用。太棒了!但是,我更喜欢使用附加到我的函数的属性来连接我的路由处理程序。我不知道使用属性函数和传入全局状态的语法(如果允许)。

下面是来自https://docs.rs/actix-web/1.0.2/actix_web/web/struct.Data.html的actix-web文档的示例

代码语言:javascript
复制
use std::sync::Mutex;
use actix_web::{web, App};

struct MyData {
    counter: usize,
}

/// Use `Data<T>` extractor to access data in handler.
fn index(data: web::Data<Mutex<MyData>>) {
    let mut data = data.lock().unwrap();
    data.counter += 1;
}

fn main() {
    let data = web::Data::new(Mutex::new(MyData{ counter: 0 }));

    let app = App::new()
        // Store `MyData` in application storage.
        .register_data(data.clone())
        .service(
            web::resource("/index.html").route(
                web::get().to(index)));
}

请注意web::Data是如何传递给名为index的路由处理程序的。

下面是我的一些代码片段。

代码语言:javascript
复制
use actix_web::{get, App, HttpResponse, HttpServer, Responder};
pub mod request;
pub mod routes;

const SERVICE_NAME : &str = "Shy Rules Engine";
const SERVICE_VERSION : &str  = "0.1";

#[get("/")]
fn index() -> impl Responder {
    HttpResponse::Ok().body(format!("{} version {}", SERVICE_NAME, SERVICE_VERSION))
}

mod expression_execute {

  #[post("/expression/execute")]
  fn route(req: web::Json<ExpressionExecuteRequest>) -> HttpResponse {

    // ... lots of code omitted ...

    if response.has_error() {
        HttpResponse::Ok().json(response)
    }
    else {
        HttpResponse::BadRequest().json(response)
    }
  }

}

pub fn shy_service(ip : &str, port : &str) {
    HttpServer::new(|| {
        App::new()
            .service(index)
            .service(expression_execute::route)
    })
    .bind(format!("{}:{}", ip, port))
    .unwrap()
    .run()
    .unwrap();
}

注意我是如何调用App::service方法来连接我的路由处理程序的。

还要注意我的路由处理程序没有接收全局状态(因为我还没有将它添加到我的应用程序中)。如果我使用与文档类似的模式使用register_data创建全局应用程序数据,那么我应该对方法签名、getpost属性以及其他任何东西进行哪些更改,以便将全局状态传递给处理程序?

或者不能使用getpost属性来访问全局状态?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-18 15:30:54

你列举的两个案例真的没有太大区别:

代码语言:javascript
复制
//# actix-web = "1.0.8"
use actix_web::{get, web, App, HttpResponse, HttpServer, Responder};
use std::sync::Mutex;

const SERVICE_NAME : &str = "Shy Rules Engine";
const SERVICE_VERSION : &str  = "0.1";

struct MyData {
    counter: usize,
}

#[get("/")]
fn index(data: web::Data<Mutex<MyData>>) -> impl Responder {
    let mut data = data.lock().unwrap();
    data.counter += 1;
    println!("Endpoint visited: {}", data.counter);
    HttpResponse::Ok().body(format!("{} version {}", SERVICE_NAME, SERVICE_VERSION))
}

pub fn shy_service(ip : &str, port : &str) {
    let data = web::Data::new(Mutex::new(MyData{ counter: 0 }));

    HttpServer::new(move || {
        App::new()
            .register_data(data.clone())
            .service(index)
    })
    .bind(format!("{}:{}", ip, port))
    .unwrap()
    .run()
    .unwrap();
}

fn main() {
    shy_service("127.0.0.1", "8080");
}

只需对http端点执行curl命令,即可验证它是否正常工作。对于multiple extractors,您必须使用元组:

代码语言:javascript
复制
    #[post("/expression/execute")]
    fn route((req, data): (web::Json<ExpressionExecuteRequest>, web::Data<Mutex<MyData>>)) -> HttpResponse {
        unimplemented!()
    }
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58436748

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档