文章目录
- 一、client
- 1.1 post
reqwest 实现的 http server 和 client
用 https://github.com/seanmonstar/reqwest
cargo add reqwest -F json
cargo add tokio -F full
一、client
1.1 post
async fn http_post<T: Serialize>(addr: String, body: T) -> Result<(), reqwest::Error> {
let client = reqwest::Client::new();
let resp = client.post(addr.clone()).json(&body).send().await?;
if resp.status() == StatusCode::OK || resp.status() == StatusCode::NO_CONTENT {
println!(
"http调用 {:?} 成功, 返回码 {:?}",
addr.clone(),
resp.status()
);
} else {
let body_json = serde_json::to_string(&body).unwrap_or_else(|_| "".to_string());
println!(
"http调用 {:?} 成功, 返回码 {:?}, body: {}, 返回体 {:?}",
addr.clone(),
resp.status(),
body_json,
resp.text().await?
);
}
Ok(())
}
调用方式如下:
async fn f(arg: Arg) -> Result<(), reqwest::Error> {
#[derive(Debug, Serialize)]
struct Body {
#[serde(rename = "UserID")]
user_id: i64,
#[serde(rename = "Arr")]
arr: Vec<String>,
}
let addr = format!("http://{}:123/v1/user", arg.server_ip);
let req_body = Body {
user_id: 1,
arr: vec![
"a".to_string(),
"b".to_string(),
],
};
http_post(addr.clone(), req_body).await?;
Ok(())
}