1

如何反序列化 actix_web 表单数据并将其序列化为 csv 文件?是否可以使用一个结构?如何覆盖 csv 错误场景?我正在尝试x-www-form-urlencoded在我的第一个 Rust 程序中将表单数据保存到 csv 文件中,但是与 Ruby 相比,这种语言非常严格;)如何将负责保存到 csv 的代码移动到专用函数?

extern crate csv;
#[macro_use]
extern crate serde_derive;
use actix_web::{middleware, web, App, HttpResponse, HttpServer, Result};
use serde::{Deserialize, Serialize};
use std::io;

#[derive(Serialize, Deserialize)]
struct FormData {
    email: String,
    fullname: String,
    message: String,
}

async fn contact(form: web::Form<FormData>) -> Result<String> {
    let mut wtr = csv::Writer::from_writer(io::stdout());
    wtr.serialize(form)?;
    wtr.flush()?;

    Ok(format!("Hello {}!", form.fullname))
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(web::resource("/contact").route(web::post().to(contact)))
    })
    .bind("127.0.0.1:8000")?
    .run()
    .await
}

我有以下错误:

error[E0277]: the trait bound `actix_web::types::form::Form<FormData>: _IMPL_DESERIALIZE_FOR_FormData::_serde::Serialize` is not satisfied
  --> src/main.rs:46:19
   |
46 |     wtr.serialize(form)?;
   |                   ^^^^ the trait `_IMPL_DESERIALIZE_FOR_FormData::_serde::Serialize` is not implemented for `actix_web::types::form::Form<FormData>`

error[E0277]: the trait bound `csv::Error: actix_http::error::ResponseError` is not satisfied
  --> src/main.rs:46:24
   |
46 |     wtr.serialize(form)?;
   |                        ^ the trait `actix_http::error::ResponseError` is not implemented for `csv::Error`
   |
   = note: required because of the requirements on the impl of `std::convert::From<csv::Error>` for `actix_http::error::Error`
   = note: required by `std::convert::From::from`

error: aborting due to 2 previous errors

使用的库:

[dependencies]
actix-web = "2.0.0"
actix-rt = "1.0.0"
serde = "1.0"
serde_derive = "1.0.110"
csv = "1.1"
4

1 回答 1

1

您需要获取 web::form 数据的内部结构。

pub async fn contact(form: web::Form<FormData>) -> HttpResponse<Body> {
  let mut wtr = csv::Writer::from_writer(io::stdout());
  wtr.serialize(form.into_inner());
  wtr.flush();

  HttpResponse::Ok().body("".to_string())
}
于 2020-06-29T19:03:49.837 回答