(
server_url: &str,
method: &str,
path: &str,
body: Option<&Value>,
)
| 9 | } |
| 10 | |
| 11 | fn http_request( |
| 12 | server_url: &str, |
| 13 | method: &str, |
| 14 | path: &str, |
| 15 | body: Option<&Value>, |
| 16 | ) -> anyhow::Result<Vec<u8>> { |
| 17 | let endpoint = HttpEndpoint::parse(server_url)?; |
| 18 | let mut stream = std::net::TcpStream::connect((endpoint.host.as_str(), endpoint.port)) |
| 19 | .with_context(|| format!("connect to SimDeck service at {server_url}"))?; |
| 20 | stream.set_read_timeout(Some(Duration::from_secs(180)))?; |
| 21 | stream.set_write_timeout(Some(Duration::from_secs(5)))?; |
| 22 | let body = body.map(serde_json::to_vec).transpose()?; |
| 23 | let request = if let Some(body) = body.as_ref() { |
| 24 | format!( |
| 25 | "{method} {path} HTTP/1.1\r\nHost: {}\r\nOrigin: {}\r\nAccept: application/json\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n", |
| 26 | endpoint.host_header(), |
| 27 | endpoint.origin(), |
| 28 | body.len(), |
| 29 | ) |
| 30 | } else { |
| 31 | format!( |
| 32 | "{method} {path} HTTP/1.1\r\nHost: {}\r\nOrigin: {}\r\nAccept: application/json\r\nConnection: close\r\n\r\n", |
| 33 | endpoint.host_header(), |
| 34 | endpoint.origin(), |
| 35 | ) |
| 36 | }; |
| 37 | stream.write_all(request.as_bytes())?; |
| 38 | if let Some(body) = body.as_ref() { |
| 39 | stream.write_all(body)?; |
| 40 | } |
| 41 | |
| 42 | let mut response = Vec::new(); |
| 43 | stream.read_to_end(&mut response)?; |
| 44 | let (status, headers, body) = parse_http_response(&response)?; |
| 45 | let body = if response_is_chunked(&headers) { |
| 46 | decode_chunked_body(body)? |
| 47 | } else { |
| 48 | body.to_vec() |
| 49 | }; |
| 50 | if !(200..300).contains(&status) { |
| 51 | let message = String::from_utf8_lossy(&body).trim().to_owned(); |
| 52 | anyhow::bail!( |
| 53 | "SimDeck service returned HTTP {status}{}", |
| 54 | if message.is_empty() { |
| 55 | String::new() |
| 56 | } else { |
| 57 | format!(": {message}") |
| 58 | } |
| 59 | ); |
| 60 | } |
| 61 | Ok(body) |
| 62 | } |
| 63 | |
| 64 | struct HttpEndpoint { |
| 65 | host: String, |
no test coverage detected