Skip to main content

ling_net/
http.rs

1//! HTTP server (axum) and client (reqwest) for ling-net.
2
3use crate::types::{HttpMethod, Request, Response};
4use crate::error::NetError;
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.send().await
28            .map_err(|e| NetError::Http(e.to_string()))?;
29        let status = resp.status().as_u16();
30        let headers = resp.headers()
31            .iter()
32            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string()))
33            .collect();
34        let body = resp.bytes().await
35            .map_err(|e| NetError::Http(e.to_string()))?
36            .to_vec();
37        Ok(Response { status, headers, body })
38    }
39    #[cfg(target_arch = "wasm32")]
40    {
41        Err(NetError::Unsupported("HTTP not available on WASM via reqwest".into()))
42    }
43}
44
45/// Simple in-process HTTP GET helper.
46pub async fn get(url: &str) -> Result<Vec<u8>, NetError> {
47    send(Request {
48        method: HttpMethod::Get,
49        url: url.to_string(),
50        headers: Default::default(),
51        body: None,
52    })
53    .await
54    .map(|r| r.body)
55}
56
57/// Simple in-process HTTP POST helper.
58pub async fn post(url: &str, body: Vec<u8>) -> Result<Vec<u8>, NetError> {
59    send(Request {
60        method: HttpMethod::Post,
61        url: url.to_string(),
62        headers: Default::default(),
63        body: Some(body),
64    })
65    .await
66    .map(|r| r.body)
67}