-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdev_server.rs
284 lines (250 loc) · 8.21 KB
/
dev_server.rs
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
use crate::{
anyhow::{bail, Context, Result},
camino::Utf8Path,
clap, Watch,
};
use std::{
ffi, fs,
io::{prelude::*, BufReader},
net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, TcpStream},
path::{Path, PathBuf},
process,
};
/// A simple HTTP server useful during development.
///
/// It can watch the source code for changes and restart a provided command.
///
/// Get the files at `watch_path` and serve them at a given IP address
/// (127.0.0.1:8000 by default). An optional command can be provided to restart
/// the build when changes are detected.
///
/// # Usage
///
/// ```rust,no_run
/// use std::process;
/// use xtask_wasm::{
/// anyhow::Result,
/// clap,
/// default_dist_dir,
/// };
///
/// #[derive(clap::Parser)]
/// enum Opt {
/// Start(xtask_wasm::DevServer),
/// Dist,
/// }
///
/// fn main() -> Result<()> {
/// let opt: Opt = clap::Parser::parse();
///
/// match opt {
/// Opt::Start(mut dev_server) => {
/// log::info!("Starting the development server...");
/// dev_server.arg("dist").start(default_dist_dir(false))?;
/// }
/// Opt::Dist => todo!("build project"),
/// }
///
/// Ok(())
/// }
/// ```
///
/// Add a `start` subcommand that will run `cargo xtask dist`, watching for
/// changes in the workspace and serve the files in the default dist directory
/// (`target/debug/dist` for non-release) at a given IP address.
#[non_exhaustive]
#[derive(Debug, clap::Parser)]
#[clap(
about = "A simple HTTP server useful during development.",
long_about = "A simple HTTP server useful during development.\n\
It can watch the source code for changes."
)]
pub struct DevServer {
/// IP address to bind. Default to `127.0.0.1`.
#[clap(long, default_value = "127.0.0.1")]
pub ip: IpAddr,
/// Port number. Default to `8000`.
#[clap(long, default_value = "8000")]
pub port: u16,
/// Watch object for detecting changes.
///
/// # Note
///
/// Used only if `command` is set.
#[clap(flatten)]
pub watch: Watch,
/// Command executed when a change is detected.
#[clap(skip)]
pub command: Option<process::Command>,
/// Use another file path when the URL is not found.
#[clap(skip)]
pub not_found_path: Option<PathBuf>,
}
impl DevServer {
/// Set the dev-server binding address.
pub fn address(mut self, ip: IpAddr, port: u16) -> Self {
self.ip = ip;
self.port = port;
self
}
/// Set the command that is executed when a change is detected.
pub fn command(mut self, command: process::Command) -> Self {
self.command = Some(command);
self
}
/// Adds an argument to pass to the command executed when changes are
/// detected.
///
/// This will use the xtask command by default.
pub fn arg<S: AsRef<ffi::OsStr>>(mut self, arg: S) -> Self {
self.set_xtask_command().arg(arg);
self
}
/// Adds multiple arguments to pass to the command executed when changes are
/// detected.
///
/// This will use the xtask command by default.
pub fn args<I, S>(mut self, args: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<ffi::OsStr>,
{
self.set_xtask_command().args(args);
self
}
/// Use another file path when the URL is not found.
pub fn not_found(mut self, path: impl Into<PathBuf>) -> Self {
self.not_found_path.replace(path.into());
self
}
/// Start the server, serving the files at `served_path`.
///
/// [`crate::default_dist_dir`] should be used to get the dist directory
/// that needs to be served.
pub fn start(self, served_path: impl AsRef<Path>) -> Result<()> {
let watch_process = if let Some(command) = self.command {
// NOTE: the path needs to exists in order to be excluded because it is canonicalize
let _ = std::fs::create_dir_all(&served_path);
let watch = self.watch.exclude_path(&served_path);
let handle = std::thread::spawn(|| match watch.run(command) {
Ok(()) => log::trace!("Starting to watch"),
Err(err) => log::error!("an error occurred when starting to watch: {}", err),
});
Some(handle)
} else {
None
};
serve(
self.ip,
self.port,
served_path,
self.not_found_path.as_deref(),
)
.context("an error occurred when starting to serve")?;
if let Some(handle) = watch_process {
handle.join().expect("an error occurred when exiting watch");
}
Ok(())
}
fn set_xtask_command(&mut self) -> &mut process::Command {
if self.command.is_none() {
self.command = Some(crate::xtask_command());
}
self.command.as_mut().unwrap()
}
}
impl Default for DevServer {
fn default() -> DevServer {
DevServer {
ip: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
port: 8000,
watch: Default::default(),
command: None,
not_found_path: None,
}
}
}
fn serve(
ip: IpAddr,
port: u16,
served_path: impl AsRef<Path>,
not_found_path: Option<impl AsRef<Path>>,
) -> Result<()> {
let address = SocketAddr::new(ip, port);
let listener = TcpListener::bind(address).context("cannot bind to the given address")?;
log::info!("Development server running at: http://{}", &address);
for mut stream in listener.incoming().filter_map(|x| x.ok()) {
respond_to_request(&mut stream, &served_path, not_found_path.as_ref()).unwrap_or_else(
|e| {
let _ = stream.write("HTTP/1.1 400 BAD REQUEST\r\n\r\n".as_bytes());
log::error!("an error occurred: {}", e);
},
);
}
Ok(())
}
fn respond_to_request(
stream: &mut TcpStream,
dist_dir_path: impl AsRef<Path>,
not_found_path: Option<impl AsRef<Path>>,
) -> Result<()> {
let mut reader = BufReader::new(stream);
let mut request = String::new();
reader.read_line(&mut request)?;
let requested_path = request
.split_whitespace()
.nth(1)
.context("Could not find path in request")?;
let requested_path = requested_path
.split_once('?')
.map(|(prefix, _suffix)| prefix)
.unwrap_or(requested_path);
log::debug!("<-- {}", requested_path);
let rel_path = Path::new(requested_path.trim_matches('/'));
let mut full_path = dist_dir_path.as_ref().join(rel_path);
if full_path.is_dir() {
if full_path.join("index.html").exists() {
full_path = full_path.join("index.html")
} else if full_path.join("index.htm").exists() {
full_path = full_path.join("index.htm")
} else {
bail!("no index.html in {}", full_path.display());
}
}
let stream = reader.get_mut();
if let Some(path) = not_found_path {
if !full_path.is_file() {
full_path = dist_dir_path.as_ref().join(path);
}
}
if full_path.is_file() {
log::debug!("--> {}", full_path.display());
let full_path_extension = Utf8Path::from_path(&full_path)
.context("request path contains non-utf8 characters")?
.extension();
let content_type = match full_path_extension {
Some("html") => "text/html;charset=utf-8",
Some("css") => "text/css;charset=utf-8",
Some("js") => "application/javascript",
Some("wasm") => "application/wasm",
_ => "application/octet-stream",
};
stream
.write(
format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: {}\r\n\r\n",
full_path.metadata()?.len(),
content_type,
)
.as_bytes(),
)
.context("cannot write response")?;
std::io::copy(&mut fs::File::open(&full_path)?, stream)?;
} else {
log::error!("--> {} (404 NOT FOUND)", full_path.display());
stream
.write("HTTP/1.1 404 NOT FOUND\r\n\r\n".as_bytes())
.context("cannot write response")?;
}
Ok(())
}