Skip to main content

ling_net/
http.rs

1//! HTTP server (axum) and client (reqwest) for ling-net.
2
3use crate::error::NetError;
4use crate::types::{HttpMethod, Request, Response};
5
6/// Make an outgoing HTTP request.
7pub async fn send(req: Request) -> Result<Response, NetError> {
8    #[cfg(not(target_arch = "wasm32"))]
9    {
10        let client = reqwest::Client::new();
11        let method = match req.method {
12            HttpMethod::Get => reqwest::Method::GET,
13            HttpMethod::Post => reqwest::Method::POST,
14            HttpMethod::Put => reqwest::Method::PUT,
15            HttpMethod::Delete => reqwest::Method::DELETE,
16            HttpMethod::Patch => reqwest::Method::PATCH,
17            HttpMethod::Head => reqwest::Method::HEAD,
18            HttpMethod::Options => reqwest::Method::OPTIONS,
19        };
20        let mut builder = client.request(method, &req.url);
21        for (k, v) in &req.headers {
22            builder = builder.header(k, v);
23        }
24        if let Some(body) = req.body {
25            builder = builder.body(body);
26        }
27        let resp = builder
28            .send()
29            .await
30            .map_err(|e| NetError::Http(e.to_string()))?;
31        let status = resp.status().as_u16();
32        let headers = resp
33            .headers()
34            .iter()
35            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
36            .collect();
37        let body = resp
38            .bytes()
39            .await
40            .map_err(|e| NetError::Http(e.to_string()))?
41            .to_vec();
42        Ok(Response { status, headers, body })
43    }
44    #[cfg(target_arch = "wasm32")]
45    {
46        Err(NetError::Unsupported(
47            "HTTP not available on WASM via reqwest".into(),
48        ))
49    }
50}
51
52/// Simple in-process HTTP GET helper.
53pub async fn get(url: &str) -> Result<Vec<u8>, NetError> {
54    send(Request {
55        method: HttpMethod::Get,
56        url: url.to_string(),
57        headers: Default::default(),
58        body: None,
59    })
60    .await
61    .map(|r| r.body)
62}
63
64/// Simple in-process HTTP POST helper.
65pub async fn post(url: &str, body: Vec<u8>) -> Result<Vec<u8>, NetError> {
66    send(Request {
67        method: HttpMethod::Post,
68        url: url.to_string(),
69        headers: Default::default(),
70        body: Some(body),
71    })
72    .await
73    .map(|r| r.body)
74}