abstio/
http.rs

1use anyhow::{Context, Result};
2
3/// Performs an HTTP POST request and returns the response.
4pub async fn http_post<U: AsRef<str>, B: Into<reqwest::Body>>(url: U, body: B) -> Result<String> {
5    let url = url.as_ref();
6    info!("HTTP POST to {}", url);
7    let resp = reqwest::Client::new()
8        .post(url)
9        .body(body)
10        .send()
11        .await
12        .with_context(|| url.to_string())?;
13    let status = resp.status();
14    let text = resp.text().await.with_context(|| url.to_string())?;
15    // With error_for_status{_ref}, it's unclear how to propagate errors and also get the error
16    // message from the body, so do this
17    if status.is_client_error() || status.is_server_error() {
18        bail!("HTTP error {}: {}", status, text);
19    }
20    Ok(text)
21}
22
23/// Performs an HTTP GET request and returns the raw response. Unlike the variations in
24/// download.rs, no progress -- but it works on native and web.
25pub async fn http_get<I: AsRef<str>>(url: I) -> Result<Vec<u8>> {
26    let url = url.as_ref();
27    info!("HTTP GET {}", url);
28    let resp = reqwest::get(url).await?.error_for_status()?.bytes().await?;
29    Ok(resp.to_vec())
30}