| 16 | use crate::parser::BuiltinCommand; |
| 17 | |
| 18 | pub async fn run_request( |
| 19 | mut cmd: BuiltinCommand, |
| 20 | _: &mut State, |
| 21 | ) -> Result<ControlFlow, anyhow::Error> { |
| 22 | let url = cmd.args.string("url")?; |
| 23 | let method: Method = cmd.args.parse("method")?; |
| 24 | let content_type = cmd.args.opt_string("content-type"); |
| 25 | let further_accepted_status_codes = match cmd.args.opt_string("accept-additional-status-codes") |
| 26 | { |
| 27 | Some(s) => s |
| 28 | .split(',') |
| 29 | .map(|s| s.parse::<u16>().unwrap()) |
| 30 | .collect::<HashSet<u16>>(), |
| 31 | None => HashSet::new(), |
| 32 | }; |
| 33 | let body = cmd.input.join("\n"); |
| 34 | |
| 35 | println!("$ http-request {} {}\n{}", method, url, body); |
| 36 | |
| 37 | let client = reqwest::Client::new(); |
| 38 | |
| 39 | let mut request = client.request(method, &url).body(body); |
| 40 | |
| 41 | if let Some(value) = &content_type { |
| 42 | request = request.header(CONTENT_TYPE, value); |
| 43 | } |
| 44 | |
| 45 | let response = request.send().await?; |
| 46 | let status = response.status(); |
| 47 | |
| 48 | println!("{}\n{}", status, response.text().await?); |
| 49 | |
| 50 | if status.is_success() || further_accepted_status_codes.contains(&status.as_u16()) { |
| 51 | Ok(ControlFlow::Continue) |
| 52 | } else { |
| 53 | bail!("http request returned failing status: {}", status) |
| 54 | } |
| 55 | } |