Send a POST request with JSON body and receive JSON response
(
&self,
url: &str,
body: &T,
)
| 195 | |
| 196 | /// Send a POST request with JSON body and receive JSON response |
| 197 | pub async fn post_json<T: Serialize, R: DeserializeOwned>( |
| 198 | &self, |
| 199 | url: &str, |
| 200 | body: &T, |
| 201 | ) -> Result<R> { |
| 202 | let body = serde_json::to_vec(body).context("failed to serialize request body")?; |
| 203 | |
| 204 | let request = hyper::Request::builder() |
| 205 | .method(hyper::Method::POST) |
| 206 | .uri(url) |
| 207 | .header("content-type", "application/json") |
| 208 | .body(Full::new(Bytes::from(body))) |
| 209 | .context("failed to build request")?; |
| 210 | |
| 211 | let response = self |
| 212 | .client |
| 213 | .request(request) |
| 214 | .await |
| 215 | .with_context(|| format!("failed to send request to {url}"))?; |
| 216 | |
| 217 | if !response.status().is_success() { |
| 218 | anyhow::bail!("request failed: {}", response.status()); |
| 219 | } |
| 220 | |
| 221 | let body = response |
| 222 | .into_body() |
| 223 | .collect() |
| 224 | .await |
| 225 | .context("failed to read response body")? |
| 226 | .to_bytes(); |
| 227 | |
| 228 | serde_json::from_slice(&body).context("failed to parse response") |
| 229 | } |
| 230 | |
| 231 | /// Send a POST request with msgpack + gzip encoded body and receive msgpack + gzip response |
| 232 | pub async fn post_compressed_msg<T: Serialize, R: DeserializeOwned>( |
no test coverage detected