async fn handle_index()-> Response { let mut name_list: Vec<Name> = Vec::new(); let name1 = Name { family: "tanaka".to_string(), first: "taro".to_string(), age: 12}; let name2 = Name { family: "yamada".to_string(), first: "koji".to_string(), age: 13}; let name3 = Name { family: "okamoto".to_string(), first: "ai".to_string(), age: 14}; name_list.push(name1); name_list.push(name2); name_list.push(name3); let name_list_serialized = serde_json::json!(&name_list); let mut post_url = format!("http://192.168.33.10:3000/fetch"); let client = reqwest::Client::new(); let resp = client.post(post_url) .header(reqwest::header::CONTENT_TYPE, "application/json") .json(&name_list_serialized) .send() .await .unwrap(); // println!("{:?}", resp); "All good".into_response() } async fn handle_fetch(extract::Json(names): extract::Json<Vec<Name>>)-> Response { println!("get names: {:?}", names); let file_path = format!("./data/names.txt"); if !Path::new(&file_path.clone()).exists() { let mut file = File::create(file_path.clone()).unwrap(); for name in names { let serialized: Vec<u8> = serde_json::to_vec(&name).unwrap(); file.write_all(&serialized).expect("write failed"); file.write_all(b"\n").expect("write failed"); } println!("done"); } else { println!("file exist"); } "All good".into_response() }
names.txt
{“family”:”tanaka”,”first”:”taro”,”age”:12}
{“family”:”yamada”,”first”:”koji”,”age”:13}
{“family”:”okamoto”,”first”:”ai”,”age”:14}
うん、期待通りです。