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
89
90
91
92
93
94
95
96
97
98
99
100
use reqwest::blocking::{Client, Response};
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use reqwest::Error;
use reqwest::Url;
use serde_json::Value;
static BASE_URL: &str = "https://api.line.me/v2/bot";
#[derive(Debug)]
pub struct HttpClient {
client: Client,
headers: HeaderMap,
endpoint_base: String,
}
impl HttpClient {
pub fn new(channel_token: &str) -> HttpClient {
let mut headers = HeaderMap::new();
if let Ok(v) = format!("Bearer {}", channel_token).parse::<String>() {
if let Ok(header_value) = HeaderValue::from_str(&v) {
headers.insert(AUTHORIZATION, header_value);
}
}
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
HttpClient {
client: Client::new(),
headers: headers,
endpoint_base: String::from(BASE_URL),
}
}
pub fn get(
&self,
endpoint: &str,
query: Vec<(&str, &str)>,
data: Value,
) -> Result<Response, Error> {
let uri = Url::parse(&format!("{}{}", self.endpoint_base, endpoint)).unwrap();
self.client
.get(uri)
.query(&query)
.headers(self.headers.clone())
.json(&data)
.send()
}
pub fn post(&self, endpoint: &str, data: Value) -> Result<Response, Error> {
let uri = Url::parse(&format!("{}{}", self.endpoint_base, endpoint)).unwrap();
self.client
.post(uri)
.headers(self.headers.clone())
.json(&data)
.send()
}
pub fn put(&self, endpoint: &str, data: Value) -> Result<Response, Error> {
let uri = Url::parse(&format!("{}{}", self.endpoint_base, endpoint)).unwrap();
self.client
.put(uri)
.headers(self.headers.clone())
.json(&data)
.send()
}
pub fn delete(&self, endpoint: &str, data: Value) -> Result<Response, Error> {
let uri = Url::parse(&format!("{}{}", self.endpoint_base, endpoint)).unwrap();
self.client
.delete(uri)
.headers(self.headers.clone())
.json(&data)
.send()
}
}