use actix_web::{put, web, HttpRequest, HttpResponse, Responder, Result}; use bank::account::AccountError; use serde::Serialize; use crate::handlers::error::HttpAccountError; use crate::handlers::AmountData; use crate::AppState; #[derive(Serialize)] struct AccountCreated { nr: String, } #[put("/{nr}")] pub async fn route( info: web::Path, form: web::Form, data: web::Data, req: HttpRequest, ) -> Result { let nr = info.into_inner(); let amount = form.amount; if amount <= 0_f64 { return Err(HttpAccountError(AccountError::InvalidAmount).into()); } info!("updating account {}...", nr); let bank = data.bank.read().unwrap(); match bank.accounts.get(&nr) { None => Err(HttpAccountError(AccountError::NotFound).into()), Some(account) => { let mut account = account.write().unwrap(); let hash = account.hash_string(); if let Some(etag) = req.headers().get("If-Match") { let etag = etag.to_str().unwrap_or(""); if etag != hash { Ok(HttpResponse::PreconditionFailed().finish()) } else { account.balance = amount; Ok(HttpResponse::Ok().finish()) } } else { Ok(HttpResponse::PreconditionRequired().finish()) } } } }