0

我有一个从请求正文反序列化的用户结构。我想根据从数据库接收到的数据填充User结构(字段名)的数据并返回响应。

  1. 不用复制,从数据库数据中借用用户名,存储在全局结构中
  2. 返回具有填充名称的相同用户结构的响应

我使用 tokio::task::spawn_blocking 是因为实际项目中有阻塞操作

lazy_static! {
    pub static ref USER_DATA: Mutex<Arc<HashMap<String, String>>> = Mutex::new(Arc::new(Default::default()));
}

#[derive(Deserialize, Serialize, Default)]
struct User<'a> {
    id: &'a str,

    #[serde(skip_deserializing)]
    name: &'a str
}

struct Response<'a> {
    user: web::Json<User<'a>>,
    common_data: Arc<HashMap<String, String>>
}

impl Response<'_> {
    pub fn fill_user(mut self) -> Self {
        self.user.name = self.common_data.get(self.user.id).unwrap();
        self
    }
}

impl Responder for Response<'_> {
    fn respond_to(self, req: &HttpRequest) -> HttpResponse {
        HttpResponse::build(StatusCode::OK).body(serde_json::to_string(&self.user).unwrap())
    }
}

async fn calculate(req: HttpRequest, user: web::Json<User<'static>>) -> impl Responder {

    let mut resp = Response {
        user,
        common_data: USER_DATA.lock().await.clone()
    };

    tokio::task::spawn_blocking(move || {
        resp.fill_user()
    }).await.unwrap()

}

现在我收到此错误

error: implementation of `_::_serde::Deserialize` is not general enough
  --> src\main.rs:62:46
   |
62 |             .route("/calculate", web::post().to(calculate))
   |                                              ^^ implementation of `_::_serde::Deserialize` is not general enough
   |
   = note: `User<'static>` must implement `_::_serde::Deserialize<'0>`, for any lifetime `'0`...
   = note: ...but `User<'_>` actually implements `_::_serde::Deserialize<'1>`, for some specific lifetime `'1`
4

0 回答 0