0

What is the simplest way to get json from the HttpRequest into a struct you created. Here is the main.rs

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
  HttpServer::new(|| {
    App::new()
      .data(web::JsonConfig::default().limit(4096))
      .data(connect())
      .service(web::resource("/insert").route(web::post().to(handlers::tours::insert)))
  })
  .bind("127.0.0.1:8088")
  .unwrap()
  .run()
  .await
}

And here is the struct in model/tour.rs:

#[derive(Serialize, Deserialize, Insertable)]
pub struct TourForm {
  pub name: String,
}

And here is the handler in handlers/tours.rs::

pub async fn insert(
  tour_form: web::Json<TourForm>,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.name))
}

I tried this variation because I thought this would make the code very simple:

pub async fn insert(
  tour_form: TourForm,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.name))
}

But got the error:

^^ the trait `actix_web::extract::FromRequest` is not implemented for `model::tour::TourForm`

Should I implement the FromRequest function into the TourForm struct or is there an easier way?

Apothan
  • 187
  • 1
  • 2
  • 9

1 Answers1

0

I was able to get the TourForm object out of the web::Json simply by doing tour_form.0

pub async fn insert(
  tour_form: web::Json<TourForm>,
  pool: web::Data<MysqlPool>,
) -> Result<HttpResponse, HttpResponse> {
  Ok(HttpResponse::Ok().json(&tour_form.0))
}
Apothan
  • 187
  • 1
  • 2
  • 9