space_lib/
http.rs

1use crate::{common::Method, ffi, Result};
2
3pub struct Request {
4    url: String,
5    method: Method,
6    headers: Vec<String>,
7    queries: Vec<String>,
8}
9
10impl Request {
11    /// Create a new request with method.
12    pub fn new<T: Into<String>>(url: T, method: Method) -> Self {
13        Self {
14            url: url.into(),
15            method,
16            headers: Vec::new(),
17            queries: Vec::new(),
18        }
19    }
20
21    /// Make a GET request.
22    pub fn get<T: Into<String>>(url: T) -> Self {
23        Self::new(url, Method::GET)
24    }
25
26    /// Make a POST request.
27    pub fn post<T: Into<String>>(url: T) -> Self {
28        Self::new(url, Method::POST)
29    }
30
31    /// Make a DELETE request.
32    pub fn delete<T: Into<String>>(url: T) -> Self {
33        Self::new(url, Method::DELETE)
34    }
35
36    /// Make a HEAD request.
37    pub fn head<T: Into<String>>(url: T) -> Self {
38        Self::new(url, Method::HEAD)
39    }
40
41    /// Make a PATCH request.
42    pub fn patch<T: Into<String>>(url: T) -> Self {
43        Self::new(url, Method::PATCH)
44    }
45
46    /// Make a PUT request.
47    pub fn put<T: Into<String>>(url: T) -> Self {
48        Self::new(url, Method::PUT)
49    }
50
51    /// Set a header field.
52    pub fn set<T: ToString, U: ToString>(mut self, header: T, value: U) -> Self {
53        self.headers.extend([header.to_string(), value.to_string()]);
54        self
55    }
56
57    /// Set a query parameter.
58    pub fn query<T: ToString, U: ToString>(mut self, param: T, value: U) -> Self {
59        self.queries.extend([param.to_string(), value.to_string()]);
60        self
61    }
62
63    /// Send the request.
64    pub fn call(self) -> Result<Response> {
65        let bytes = ffi::call_request(self.url, self.headers, self.queries, self.method)?;
66        Ok(Response { bytes })
67    }
68}
69
70pub struct Response {
71    bytes: Vec<u8>,
72}
73
74impl Response {
75    pub fn into_vec(self) -> Vec<u8> {
76        self.bytes
77    }
78
79    pub fn into_string(self) -> Result<String> {
80        Ok(std::str::from_utf8(&self.bytes).map(|it| it.to_string())?)
81    }
82
83    #[cfg(feature = "json")]
84    pub fn into_json<T: serde::de::DeserializeOwned>(self) -> Result<T> {
85        let json = std::str::from_utf8(&self.bytes)?;
86        Ok(serde_json::from_str(json)?)
87    }
88}