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