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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
pub extern crate url;
pub extern crate http;
pub extern crate hyper;
pub extern crate hyper_tls;
pub extern crate tokio_core;
use tokio_core::reactor;
use hyper::Client;
use hyper::Body;
use hyper::rt::Stream;
use hyper_tls::HttpsConnector;
use http::Request;
use url::Url;
use std::collections::HashMap;
use std::cmp::Eq;
use std::hash::Hash;
use std::io;
use std::string;
#[derive(Debug)]
pub struct HttpResponse {
pub status_code: u16,
pub headers: HashMap<String, String>,
pub body: Vec<u8>,
}
#[derive(Debug)]
pub enum HttpRequestError {
UrlParseError(url::ParseError),
HttpError(http::Error),
HyperError(hyper::Error),
IOError(io::Error),
FromUtf8Error(string::FromUtf8Error),
Other(&'static str),
}
pub enum HttpBody<BK: Eq + Hash + AsRef<str>, BV: AsRef<str>> {
Binary((String, Vec<u8>)),
Text((String, String)),
FormURLEncoded(HashMap<BK, BV>),
}
pub const QUERY_EMPTY: Option<HashMap<&'static str, &'static str>> = None;
pub const BODY_EMPTY: Option<HttpBody<&'static str, &'static str>> = None;
pub const HEADERS_EMPTY: Option<HashMap<&'static str, &'static str>> = None;
fn request<QK, QV, BK, BV, HK, HV>(method: &str, url: &str, query: Option<HashMap<QK, QV>>, body: Option<HttpBody<BK, BV>>, headers: Option<HashMap<HK, HV>>) -> Result<HttpResponse, HttpRequestError>
where QK: Eq + Hash + AsRef<str>, QV: AsRef<str>,
BK: Eq + Hash + AsRef<str>, BV: AsRef<str>,
HK: Eq + Hash + AsRef<str>, HV: AsRef<str> {
let mut request_builder = Request::builder();
request_builder.method(method);
request_builder.header("User-Agent", concat!("Mozilla/5.0 (Rust; magiclen.org) EasyHyperRequest/", env!("CARGO_PKG_VERSION")));
match query {
Some(map) => {
let mut url = Url::parse(url).map_err(|err| HttpRequestError::UrlParseError(err))?;
{
let mut query = url.query_pairs_mut();
for (k, v) in map {
query.append_pair(k.as_ref(), v.as_ref());
}
}
request_builder.uri(url.to_string());
}
None => {
request_builder.uri(url);
}
}
match headers {
Some(map) => {
for (k, v) in map {
request_builder.header(k.as_ref(), v.as_ref());
}
}
None => ()
}
let request = match body {
Some(body) => {
match body {
HttpBody::Binary((content_type, vec)) => {
request_builder.header("Content-Type", content_type);
request_builder.header("Content-Length", vec.len().to_string());
request_builder.body(Body::from(vec)).map_err(|err| HttpRequestError::HttpError(err))?
}
HttpBody::Text((content_type, text)) => {
request_builder.header("Content-Type", content_type);
request_builder.header("Content-Length", text.len().to_string());
request_builder.body(Body::from(text.into_bytes())).map_err(|err| HttpRequestError::HttpError(err))?
}
HttpBody::FormURLEncoded(map) => {
let query = {
let mut url = Url::parse("q:").map_err(|err| HttpRequestError::UrlParseError(err))?;
{
let mut query = url.query_pairs_mut();
for (k, v) in map {
query.append_pair(k.as_ref(), v.as_ref());
}
}
match url.query() {
Some(q) => {
q.as_bytes().to_vec()
}
None => Vec::new()
}
};
request_builder.header("Content-Type", "x-www-form-urlencoded");
request_builder.header("Content-Length", query.len().to_string());
request_builder.body(Body::from(query)).map_err(|err| HttpRequestError::HttpError(err))?
}
}
}
None => {
request_builder.body(Body::empty()).map_err(|err| HttpRequestError::HttpError(err))?
}
};
let client = {
let https = HttpsConnector::new(4).unwrap();
Client::builder().build::<_, hyper::Body>(https)
};
let response = client.request(request);
let mut core = reactor::Core::new().map_err(|err| HttpRequestError::IOError(err))?;
let response = core.run(response).map_err(|err| HttpRequestError::HyperError(err))?;
let mut headers = HashMap::new();
for (name, value) in response.headers() {
headers.insert(name.as_str().to_string(), String::from_utf8(value.as_bytes().to_vec()).map_err(|err| HttpRequestError::FromUtf8Error(err))?);
}
let status_code = response.status().as_u16();
let body = core.run(response.into_body().concat2()).map_err(|err| HttpRequestError::HyperError(err))?.to_vec();
Ok(HttpResponse {
status_code,
headers,
body,
})
}
pub fn head<QK, QV, HK, HV>(url: &str, query: Option<HashMap<QK, QV>>, headers: Option<HashMap<HK, HV>>) -> Result<HttpResponse, HttpRequestError>
where QK: Eq + Hash + AsRef<str>, QV: AsRef<str>,
HK: Eq + Hash + AsRef<str>, HV: AsRef<str> {
request("HEAD", url, query, BODY_EMPTY, headers)
}
pub fn get<QK, QV, HK, HV>(url: &str, query: Option<HashMap<QK, QV>>, headers: Option<HashMap<HK, HV>>) -> Result<HttpResponse, HttpRequestError>
where QK: Eq + Hash + AsRef<str>, QV: AsRef<str>,
HK: Eq + Hash + AsRef<str>, HV: AsRef<str> {
request("GET", url, query, BODY_EMPTY, headers)
}
pub fn post<QK, QV, BK, BV, HK, HV>(url: &str, query: Option<HashMap<QK, QV>>, body: Option<HttpBody<BK, BV>>, headers: Option<HashMap<HK, HV>>) -> Result<HttpResponse, HttpRequestError>
where QK: Eq + Hash + AsRef<str>, QV: AsRef<str>,
BK: Eq + Hash + AsRef<str>, BV: AsRef<str>,
HK: Eq + Hash + AsRef<str>, HV: AsRef<str> {
request("POST", url, query, body, headers)
}
pub fn put<QK, QV, BK, BV, HK, HV>(url: &str, query: Option<HashMap<QK, QV>>, body: Option<HttpBody<BK, BV>>, headers: Option<HashMap<HK, HV>>) -> Result<HttpResponse, HttpRequestError>
where QK: Eq + Hash + AsRef<str>, QV: AsRef<str>,
BK: Eq + Hash + AsRef<str>, BV: AsRef<str>,
HK: Eq + Hash + AsRef<str>, HV: AsRef<str> {
request("PUT", url, query, body, headers)
}
pub fn delete<QK, QV, BK, BV, HK, HV>(url: &str, query: Option<HashMap<QK, QV>>, body: Option<HttpBody<BK, BV>>, headers: Option<HashMap<HK, HV>>) -> Result<HttpResponse, HttpRequestError>
where QK: Eq + Hash + AsRef<str>, QV: AsRef<str>,
BK: Eq + Hash + AsRef<str>, BV: AsRef<str>,
HK: Eq + Hash + AsRef<str>, HV: AsRef<str> {
request("DELETE", url, query, body, headers)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_head() {
head("http://example.com", QUERY_EMPTY, HEADERS_EMPTY).unwrap();
head("https://magiclen.org", QUERY_EMPTY, HEADERS_EMPTY).unwrap();
}
#[test]
fn test_get() {
get("http://example.com", QUERY_EMPTY, HEADERS_EMPTY).unwrap();
get("https://magiclen.org", QUERY_EMPTY, HEADERS_EMPTY).unwrap();
}
}