-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexpanded.txt
610 lines (610 loc) · 24.9 KB
/
expanded.txt
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
#![feature(prelude_import)]
#![allow(dead_code)]
#[prelude_import]
use std::prelude::rust_2018::*;
#[macro_use]
extern crate std;
use server::Server;
use website_handler::WebsiteHandler;
use std::env;
mod http {
pub use method::Method;
pub use query_string::{QueryString, Value as QueryStringValue};
pub use request::ParseError;
pub use request::Request;
pub use response::Response;
pub use status_code::StatusCode;
pub mod method {
use std::str::FromStr;
pub enum Method {
GET,
DELETE,
POST,
PUT,
HEAD,
CONNECT,
OPTIONS,
TRACE,
PATCH,
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::core::fmt::Debug for Method {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match (&*self,) {
(&Method::GET,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "GET");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Method::DELETE,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "DELETE");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Method::POST,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "POST");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Method::PUT,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "PUT");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Method::HEAD,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "HEAD");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Method::CONNECT,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "CONNECT");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Method::OPTIONS,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "OPTIONS");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Method::TRACE,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "TRACE");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Method::PATCH,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "PATCH");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
}
}
}
impl FromStr for Method {
type Err = MethodError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"GET" => Ok(Self::GET),
"DELETE" => Ok(Self::DELETE),
"POST" => Ok(Self::POST),
"PUT" => Ok(Self::PUT),
"HEAD" => Ok(Self::HEAD),
"CONNECT" => Ok(Self::CONNECT),
"OPTIONS" => Ok(Self::OPTIONS),
"TRACE" => Ok(Self::TRACE),
"PATCH" => Ok(Self::PATCH),
_ => Err(MethodError),
}
}
}
pub struct MethodError;
}
pub mod query_string {
use ::std::collections::HashMap;
pub struct QueryString<'buf_lifetime> {
data: HashMap<&'buf_lifetime str, Value<'buf_lifetime>>,
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl<'buf_lifetime> ::core::fmt::Debug for QueryString<'buf_lifetime> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match *self {
QueryString {
data: ref __self_0_0,
} => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_struct(f, "QueryString");
let _ = ::core::fmt::DebugStruct::field(
debug_trait_builder,
"data",
&&(*__self_0_0),
);
::core::fmt::DebugStruct::finish(debug_trait_builder)
}
}
}
}
pub enum Value<'buf_lifetime> {
Single(&'buf_lifetime str),
Multiple(Vec<&'buf_lifetime str>),
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl<'buf_lifetime> ::core::fmt::Debug for Value<'buf_lifetime> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match (&*self,) {
(&Value::Single(ref __self_0),) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "Single");
let _ = ::core::fmt::DebugTuple::field(debug_trait_builder, &&(*__self_0));
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&Value::Multiple(ref __self_0),) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "Multiple");
let _ = ::core::fmt::DebugTuple::field(debug_trait_builder, &&(*__self_0));
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
}
}
}
impl<'buf_lifetime> QueryString<'buf_lifetime> {
pub fn get(&self, key: &str) -> Option<&Value> {
self.data.get(key)
}
}
impl<'buf_lifetime> From<&'buf_lifetime str> for QueryString<'buf_lifetime> {
fn from(s: &'buf_lifetime str) -> Self {
let mut data = HashMap::new();
for sub_str in s.split('&') {
let mut key = sub_str;
let mut val = "";
if let Some(i) = sub_str.find('=') {
key = &sub_str[..i];
val = &sub_str[i + 1..];
}
data.entry(key)
.and_modify(|existing: &mut Value| match existing {
Value::Single(prev_val) => {
*existing = Value::Multiple(<[_]>::into_vec(box [prev_val, val]));
}
Value::Multiple(vec) => vec.push(val),
})
.or_insert(Value::Single(val));
}
QueryString { data }
}
}
}
pub mod request {
use super::method::{Method, MethodError};
use super::QueryString;
use std::convert::TryFrom;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter, Result as FmtResult};
use std::str;
use std::str::Utf8Error;
pub struct Request<'buf_lifetime> {
path: &'buf_lifetime str,
query_string: Option<QueryString<'buf_lifetime>>,
method: Method,
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl<'buf_lifetime> ::core::fmt::Debug for Request<'buf_lifetime> {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match *self {
Request {
path: ref __self_0_0,
query_string: ref __self_0_1,
method: ref __self_0_2,
} => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_struct(f, "Request");
let _ = ::core::fmt::DebugStruct::field(
debug_trait_builder,
"path",
&&(*__self_0_0),
);
let _ = ::core::fmt::DebugStruct::field(
debug_trait_builder,
"query_string",
&&(*__self_0_1),
);
let _ = ::core::fmt::DebugStruct::field(
debug_trait_builder,
"method",
&&(*__self_0_2),
);
::core::fmt::DebugStruct::finish(debug_trait_builder)
}
}
}
}
impl<'buf_lifetime> Request<'buf_lifetime> {
pub fn path(&self) -> &str {
&self.path
}
pub fn method(&self) -> &Method {
&self.method
}
pub fn query_string(&self) -> Option<&QueryString> {
self.query_string.as_ref()
}
}
impl<'buf_lifetime> TryFrom<&'buf_lifetime [u8]> for Request<'buf_lifetime> {
type Error = ParseError;
fn try_from(buf: &'buf_lifetime [u8]) -> Result<Request<'buf_lifetime>, Self::Error> {
let request = str::from_utf8(buf)?;
let (method, request) = get_next_word(request).ok_or(ParseError::InvalidRequest)?;
let (mut path, request) =
get_next_word(request).ok_or(ParseError::InvalidRequest)?;
let (protocol, _) = get_next_word(request).ok_or(ParseError::InvalidRequest)?;
if protocol != "HTTP/1.1" {
return Err(ParseError::InvalidProtocol);
}
let method: Method = method.parse()?;
let mut query_string = None;
if let Some(i) = path.find('?') {
query_string = Some(QueryString::from(&path[i + 1..]));
path = &path[..i];
}
Ok(Self {
path,
query_string,
method,
})
}
}
fn get_next_word<'a>(request: &'a str) -> Option<(&'a str, &'a str)> {
for (i, c) in request.chars().enumerate() {
if c == ' ' || c == '\r' {
return Some((&request[..i], &request[i + 1..]));
}
}
None
}
impl From<Utf8Error> for ParseError {
fn from(_: Utf8Error) -> Self {
Self::InvalidEncoding
}
}
impl From<MethodError> for ParseError {
fn from(_: MethodError) -> Self {
Self::InvalidMethod
}
}
pub enum ParseError {
InvalidRequest,
InvalidEncoding,
InvalidProtocol,
InvalidMethod,
}
impl Error for ParseError {}
impl Display for ParseError {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_fmt(::core::fmt::Arguments::new_v1(
&[""],
&match (&self.message(),) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
))
}
}
impl Debug for ParseError {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_fmt(::core::fmt::Arguments::new_v1(
&[""],
&match (&self.message(),) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
))
}
}
impl ParseError {
fn message(&self) -> &str {
match self {
Self::InvalidRequest => "Invalid Request",
Self::InvalidEncoding => "Invalid Encoding",
Self::InvalidProtocol => "Invalid Protocol",
Self::InvalidMethod => "Invalid Method",
}
}
}
}
pub mod response {
use std::net::TcpStream;
use std::io::{Write, Result as IoResult};
use std::fmt::{Display, Formatter, Result as FmtResult};
use super::StatusCode;
pub struct Response {
status_code: StatusCode,
body: Option<String>,
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::core::fmt::Debug for Response {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match *self {
Response {
status_code: ref __self_0_0,
body: ref __self_0_1,
} => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_struct(f, "Response");
let _ = ::core::fmt::DebugStruct::field(
debug_trait_builder,
"status_code",
&&(*__self_0_0),
);
let _ = ::core::fmt::DebugStruct::field(
debug_trait_builder,
"body",
&&(*__self_0_1),
);
::core::fmt::DebugStruct::finish(debug_trait_builder)
}
}
}
}
impl Response {
pub fn new(status_code: StatusCode, body: Option<String>) -> Self {
Response { status_code, body }
}
pub fn send(&self, stream: &mut impl Write) -> IoResult<()> {
let body = match &self.body {
Some(b) => b,
None => "",
};
stream.write_fmt(::core::fmt::Arguments::new_v1(
&["HTTP/1.1 ", " ", "\r\n\r\n"],
&match (&self.status_code, &self.status_code.reason_phrase(), &body) {
(arg0, arg1, arg2) => [
::core::fmt::ArgumentV1::new(arg0, ::core::fmt::Display::fmt),
::core::fmt::ArgumentV1::new(arg1, ::core::fmt::Display::fmt),
::core::fmt::ArgumentV1::new(arg2, ::core::fmt::Display::fmt),
],
},
))
}
}
impl Display for Response {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
let body = match &self.body {
Some(b) => b,
None => "",
};
f.write_fmt(::core::fmt::Arguments::new_v1(
&["HTTP/1.1 ", " ", "\r\n\r\n"],
&match (&self.status_code, &self.status_code.reason_phrase(), &body) {
(arg0, arg1, arg2) => [
::core::fmt::ArgumentV1::new(arg0, ::core::fmt::Display::fmt),
::core::fmt::ArgumentV1::new(arg1, ::core::fmt::Display::fmt),
::core::fmt::ArgumentV1::new(arg2, ::core::fmt::Display::fmt),
],
},
))
}
}
}
pub mod status_code {
use std::fmt::{Display, Formatter, Result as FmtResult};
pub enum StatusCode {
Ok = 200,
BadRequest = 400,
NotFound = 404,
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::core::marker::Copy for StatusCode {}
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::core::clone::Clone for StatusCode {
#[inline]
fn clone(&self) -> StatusCode {
{
*self
}
}
}
#[automatically_derived]
#[allow(unused_qualifications)]
impl ::core::fmt::Debug for StatusCode {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match (&*self,) {
(&StatusCode::Ok,) => {
let debug_trait_builder = &mut ::core::fmt::Formatter::debug_tuple(f, "Ok");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&StatusCode::BadRequest,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "BadRequest");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
(&StatusCode::NotFound,) => {
let debug_trait_builder =
&mut ::core::fmt::Formatter::debug_tuple(f, "NotFound");
::core::fmt::DebugTuple::finish(debug_trait_builder)
}
}
}
}
impl StatusCode {
pub fn reason_phrase(&self) -> &str {
match self {
Self::Ok => "Ok",
Self::BadRequest => "Bad Request",
Self::NotFound => "Not Found",
}
}
}
impl Display for StatusCode {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_fmt(::core::fmt::Arguments::new_v1(
&[""],
&match (&(*self as u16),) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
))
}
}
}
}
mod server {
use crate::http::{Request, Response, StatusCode, ParseError};
use std::convert::TryFrom;
use std::io::{Read, Write};
use std::net::TcpListener;
pub struct Server {
addr: String,
}
pub trait Handler {
fn handle_request(&mut self, request: &Request) -> Response;
fn handle_bad_request(&mut self, e: &ParseError) -> Response {
{
::std::io::_print(::core::fmt::Arguments::new_v1(
&["Failed to parse request: ", "\n"],
&match (&e,) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
));
};
Response::new(StatusCode::BadRequest, None)
}
}
impl Server {
pub fn new(addr: String) -> Self {
Server { addr }
}
pub fn run(self, mut handler: impl Handler) {
{
::std::io::_print(::core::fmt::Arguments::new_v1(
&["Listening on ", "\n"],
&match (&self.addr,) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
));
};
let listener = TcpListener::bind(&self.addr).unwrap();
loop {
match listener.accept() {
Ok((mut stream, addr)) => {
{
::std::io::_print(::core::fmt::Arguments::new_v1(
&["Listening on address ", "\n"],
&match (&addr,) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
));
};
let mut buffer = [0; 1024];
match stream.read(&mut buffer) {
Ok(_) => {
{
::std::io::_print(::core::fmt::Arguments::new_v1(
&["Receive a request: ", "\n"],
&match (&String::from_utf8_lossy(&buffer),) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
));
};
let response = match Request::try_from(&buffer[..]) {
Ok(request) => handler.handle_request(&request),
Err(e) => handler.handle_bad_request(&e),
};
if let Err(e) = response.send(&mut stream) {
{
::std::io::_print(::core::fmt::Arguments::new_v1(
&["Failed to send response: ", "\n"],
&match (&e,) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
));
};
}
}
Err(e) => {
::std::io::_print(::core::fmt::Arguments::new_v1(
&["Failed to read from connection: ", "\n"],
&match (&e,) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
));
}
}
}
Err(e) => {
{
::std::io::_print(::core::fmt::Arguments::new_v1(
&["Failed to establish a connection: ", "\n"],
&match (&e,) {
(arg0,) => [::core::fmt::ArgumentV1::new(
arg0,
::core::fmt::Display::fmt,
)],
},
));
};
}
}
}
}
}
}
mod website_handler {
use super::server::Handler;
use super::http::{Request, Response, StatusCode, Method};
pub struct WebsiteHandler {
public_path: String,
}
impl WebsiteHandler {
pub fn new(public_path: String) -> Self {
Self { public_path }
}
}
impl Handler for WebsiteHandler {
fn handle_request(&mut self, request: &Request) -> Response {
match request.method() {
Method::GET => match request.path() {
"/" => Response::new(StatusCode::Ok, Some("<h1>Welcome</h1>.".to_string())),
"/hello" => Response::new(StatusCode::Ok, Some("<h1>Hello!</h1>.".to_string())),
_ => Response::new(StatusCode::NotFound, None),
},
_ => Response::new(StatusCode::NotFound, None),
}
}
}
}
fn main() {
let default_path = "/Users/fedecaccia/code/courses/rust/udemy/http_server";
let public_path = env::var("PUBLIC_PATH").unwrap();
let server = Server::new("127.0.0.1:8080".to_string());
server.run(WebsiteHandler::new(public_path));
}