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
pub mod config;
use clap::StructOpt;
use colored::Colorize;
use config::Args;
use minreq::get;
use open::that;
use std::{fs, io::prelude::*, net, process};
use url::Url;
static TEMPLATE: &str = include_str!("template.html");
pub fn run() {
let args = Args::parse();
let app = react_app(&args.file);
let port = format!("localhost:{}", args.port);
let listener = match net::TcpListener::bind(&port) {
Ok(listener) => listener,
Err(e) => {
eprintln!(
"Cannot bind to port {}, probably is busy by other process: {}",
&port, e
);
process::exit(1);
}
};
println!("{}{}", "Listening on http://".blue(), &port.blue());
if !args.simple {
that(format!("http://{}", &port)).unwrap();
};
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_connection(stream, &app);
}
}
fn react_app(file: &str) -> String {
let is_url = Url::parse(&file).is_ok();
let app = if is_url {
let resp = match get(&*file).send() {
Ok(resp) => resp,
Err(e) => {
eprintln!("Error fetching that URL: {}", e);
process::exit(1);
}
};
let app = match resp.as_str() {
Ok(app) => app,
Err(e) => {
eprintln!("Error parsing response as string: {}", e);
process::exit(1);
}
};
String::from(app)
} else {
match fs::read_to_string(file) {
Ok(app) => app,
Err(e) => {
eprintln!("Could not read file \"{}\": {}.", file.green(), e);
process::exit(1);
}
}
};
TEMPLATE.replace("// APP", &app)
}
fn handle_connection(mut stream: net::TcpStream, app: &str) {
match stream.read(&mut [0; 1024]) {
Ok(_) => println!("{}", "Request received.".green()),
Err(error) => {
eprintln!("Error reading the stream: {}", error);
process::exit(1);
}
};
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\n\r\n{}",
app.len(),
app
);
match stream.write(response.as_bytes()) {
Ok(_) => println!("[{}]", "Ping!".green()),
Err(error) => {
eprintln!("Could not write to stream: {}.", error);
process::exit(1);
}
};
stream.flush().unwrap();
}