Rust: CouchDB のデータを作成 (Create)


Cargo.toml
[package]
name = "couchdb_create"
version = "0.1.0"
edition = "2018"

[dependencies]
reqwest = { version = "0.10", features = ["json"] }
tokio = { version = "0.2", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
src/main.rs
// --------------------------------------------------------------------
/*
    couchdb_create/src/main.rs

                    Jul/26/2020
*/
// --------------------------------------------------------------------
use serde_json::json;

// --------------------------------------------------------------------
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    eprintln!("*** 開始 ***");
    let url_base = "http://localhost:5984/nagano";

    record_insert_proc(url_base,"t2021","長野",38921,"1956-2-15").await?;
    record_insert_proc(url_base,"t2022","松本",95436,"1956-10-22").await?;
    record_insert_proc(url_base,"t2023","上田",81592,"1956-9-7").await?;

    record_insert_proc(url_base,"t2024","小諸",58931,"1956-7-5").await?;
    record_insert_proc(url_base,"t2025","岡谷",25416,"1956-9-12").await?;
    record_insert_proc(url_base,"t2026","塩尻",71582,"1956-5-30").await?;


    eprintln!("*** 終了 ***");

    Ok(())
}

// --------------------------------------------------------------------
async fn record_insert_proc(url_base: &str,key_in: &str,
    name: &str,pp_in:i32,date_mod:&str)
    -> Result<(), Box<dyn std::error::Error>> {
    let url = url_base.to_owned() + "/" + key_in;
    let client_aa = reqwest::Client::new();

    println!("{}\t{}\t{}\t{}", key_in,name,pp_in,date_mod);

     let obj_new = json!({
        "name": name.to_string(),
        "population": pp_in,
        "date_mod": date_mod.to_string()
        });

    let json_str = obj_new.to_string();
    eprintln!("{}",json_str);

    let resp = client_aa
        .put(&url)
        .body(json_str)
        .send()
        .await?;

    println!("{:#?}", resp);

    Ok(())
}

// --------------------------------------------------------------------

実行

cargo run