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 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 pub fn get<T: Into<String>>(url: T) -> Self {
23 Self::new(url, Method::GET)
24 }
25
26 pub fn post<T: Into<String>>(url: T) -> Self {
28 Self::new(url, Method::POST)
29 }
30
31 pub fn delete<T: Into<String>>(url: T) -> Self {
33 Self::new(url, Method::DELETE)
34 }
35
36 pub fn head<T: Into<String>>(url: T) -> Self {
38 Self::new(url, Method::HEAD)
39 }
40
41 pub fn patch<T: Into<String>>(url: T) -> Self {
43 Self::new(url, Method::PATCH)
44 }
45
46 pub fn put<T: Into<String>>(url: T) -> Self {
48 Self::new(url, Method::PUT)
49 }
50
51 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 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 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}