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
221
222
223
224
225
226
227
228
229
230
231
use std::collections::HashMap;
use std::fmt;
use std::str::Lines;
use std::io::Error;
use connection::Connection;
pub type URL = String;
pub enum Method {
Get,
Head,
Post,
Put,
Delete,
Connect,
Options,
Trace,
Patch,
Custom(String),
}
impl fmt::Display for Method {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Method::Get => write!(f, "GET"),
&Method::Head => write!(f, "HEAD"),
&Method::Post => write!(f, "POST"),
&Method::Put => write!(f, "PUT"),
&Method::Delete => write!(f, "DELETE"),
&Method::Connect => write!(f, "CONNECT"),
&Method::Options => write!(f, "OPTIONS"),
&Method::Trace => write!(f, "TRACE"),
&Method::Patch => write!(f, "PATCH"),
&Method::Custom(ref s) => write!(f, "{}", s),
}
}
}
pub struct Request {
method: Method,
pub(crate) host: URL,
resource: URL,
headers: HashMap<String, String>,
body: Option<String>,
pub(crate) timeout: Option<u64>,
https: bool,
}
impl Request {
pub fn new<T: Into<URL>>(method: Method, url: T) -> Request {
let (host, resource, https) = parse_url(url.into());
Request {
method,
host,
resource,
headers: HashMap::new(),
body: None,
timeout: None,
https,
}
}
pub fn with_header<T: Into<String>, U: Into<String>>(mut self, key: T, value: U) -> Request {
self.headers.insert(key.into(), value.into());
self
}
pub fn with_body<T: Into<String>>(mut self, body: T) -> Request {
let body = body.into();
let body_length = body.len();
self.body = Some(body);
self.with_header("Content-Length", format!("{}", body_length))
}
pub fn with_timeout(mut self, timeout: u64) -> Request {
self.timeout = Some(timeout);
self
}
#[cfg(feature = "https")]
pub fn send(self) -> Result<Response, Error> {
if self.https {
Connection::new(self).send_https()
} else {
Connection::new(self).send()
}
}
#[cfg(not(feature = "https"))]
pub fn send(self) -> Result<Response, Error> {
if self.https {
panic!("Can't send requests to urls that start with https:// when the `https` feature is not enabled!")
} else {
Connection::new(self).send()
}
}
pub(crate) fn into_string(self) -> String {
let mut http = String::new();
http += &format!(
"{} {} HTTP/1.1\r\nHost: {}\r\n",
self.method, self.resource, self.host
);
for (k, v) in self.headers {
http += &format!("{}: {}\r\n", k, v);
}
http += "\r\n";
if let Some(body) = self.body {
http += &format!("{}", body);
}
http
}
}
pub struct Response {
pub status_code: i32,
pub reason_phrase: String,
pub headers: HashMap<String, String>,
pub body: String,
}
impl Response {
pub(crate) fn from_string(response_text: String) -> Response {
let mut lines = response_text.lines();
let status_line = lines.next().unwrap_or("");
let (status_code, reason_phrase) = parse_status_line(status_line);
let (headers, body) = parse_http_response_content(lines);
Response {
status_code,
reason_phrase,
headers,
body,
}
}
}
fn parse_url(url: URL) -> (URL, URL, bool) {
let mut first = URL::new();
let mut second = URL::new();
let mut slashes = 0;
for c in url.chars() {
if c == '/' {
slashes += 1;
} else if slashes == 2 {
first.push(c);
}
if slashes >= 3 {
second.push(c);
}
}
if second.len() == 0 {
second += "/";
}
let https = url.starts_with("https://");
if !first.contains(":") {
first += if https { ":443" } else { ":80" };
}
(first, second, https)
}
fn parse_status_line(line: &str) -> (i32, String) {
let mut split = line.split(" ");
if let Some(code) = split.nth(1) {
if let Ok(code) = code.parse::<i32>() {
if let Some(reason) = split.next() {
return (code, reason.to_string());
}
}
}
(503, "Server did not provide a status line".to_string())
}
fn parse_http_response_content(lines: Lines) -> (HashMap<String, String>, String) {
let mut headers = HashMap::new();
let mut body = String::new();
let mut writing_headers = true;
for line in lines {
if line.is_empty() {
writing_headers = false;
continue;
}
if writing_headers {
if let Some(index) = line.find(":") {
let key = line[..index].trim().to_string();
let value = line[index..].trim().to_string();
headers.insert(key, value);
}
} else {
body += &format!("{}\r\n", line);
}
}
(headers, body)
}