Files
tessera/crates/tessera-agent/src/http.rs
Tessera Agent a5ffb2c1b4 Initial Tessera backup vault (M0–M2)
Scaffold Rust workspace, React canvas, vault engine, hub API,
providers, agent wormhole path, and Docker compose per SPEC.
2026-11-09 09:59:42 +00:00

59 lines
1.9 KiB
Rust

use anyhow::{Context, Result};
use std::collections::HashMap;
use std::io::{Read, Write};
use std::net::TcpStream;
pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result<String> {
let payload = serde_json::to_string(body)?;
request("POST", url, Some(&payload), Some("application/json"), headers)
}
fn request(
method: &str,
url: &str,
body: Option<&str>,
content_type: Option<&str>,
headers: &[(&str, &str)],
) -> Result<String> {
let (host, port, path) = parse_url(url)?;
let mut stream = TcpStream::connect((host.as_str(), port)).context("connect")?;
let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n");
for (k, v) in headers {
req.push_str(&format!("{k}: {v}\r\n"));
}
if let Some(b) = body {
req.push_str(&format!("Content-Length: {}\r\n", b.len()));
if let Some(ct) = content_type {
req.push_str(&format!("Content-Type: {ct}\r\n"));
}
req.push_str("\r\n");
req.push_str(b);
} else {
req.push_str("\r\n");
}
stream.write_all(req.as_bytes())?;
let mut buf = String::new();
stream.read_to_string(&mut buf)?;
let body_start = buf.find("\r\n\r\n").map(|i| i + 4).unwrap_or(0);
Ok(buf[body_start..].trim().to_string())
}
fn parse_url(url: &str) -> Result<(String, u16, String)> {
let url = url.strip_prefix("http://").context("only http supported")?;
let (host_port, path) = url.split_once('/').unwrap_or((url, ""));
let path = if path.is_empty() {
"/".to_string()
} else {
format!("/{path}")
};
let (host, port) = if let Some((h, p)) = host_port.split_once(':') {
(h.to_string(), p.parse()?)
} else {
(host_port.to_string(), 80)
};
Ok((host, port, path))
}
#[allow(dead_code)]
pub type HeaderMap = HashMap<String, String>;