Skip to content

Commit

Permalink
Update HTTP server (#702)
Browse files Browse the repository at this point in the history
* Use native newline in HTML content

* Use native newline in text content

* Add MIME type to BMP files
  • Loading branch information
vinc authored Nov 14, 2024
1 parent 92055d5 commit 4af5cba
Showing 1 changed file with 10 additions and 18 deletions.
28 changes: 10 additions & 18 deletions src/usr/httpd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,7 @@ fn get(req: &Request, res: &mut Response) {
"Location".to_string(),
format!("{}/", req.path),
);
res.body.extend_from_slice(b"<h1>Moved Permanently</h1>\r\n");
res.body.extend_from_slice(b"<h1>Moved Permanently</h1>\n");
} else {
let mut not_found = true;
for index in INDEX {
Expand All @@ -221,16 +221,7 @@ fn get(req: &Request, res: &mut Response) {
if let Ok(buf) = fs::read_to_bytes(&real_path) {
res.code = 200;
res.mime = content_type(&real_path);
let tmp;
res.body.extend_from_slice(
if res.mime.starts_with("text/") {
tmp = String::from_utf8_lossy(&buf).to_string().
replace("\n", "\r\n");
tmp.as_bytes()
} else {
&buf
},
);
res.body.extend_from_slice(&buf);
not_found = false;
break;
}
Expand All @@ -240,22 +231,22 @@ fn get(req: &Request, res: &mut Response) {
res.code = 200;
res.mime = "text/html".to_string();
res.body.extend_from_slice(
format!("<h1>Index of {}</h1>\r\n", req.path).as_bytes()
format!("<h1>Index of {}</h1>\n", req.path).as_bytes()
);
files.sort_by_key(|f| f.name());
for file in files {
let path = format!("{}{}", req.path, file.name());
let path = format!(
"{}{}", req.path, file.name()
);
let link = format!(
"<li><a href=\"{}\">{}</a></li>\n",
path,
file.name()
"<li><a href=\"{}\">{}</a></li>\n", path, file.name()
);
res.body.extend_from_slice(link.as_bytes());
}
} else {
res.code = 404;
res.mime = "text/html".to_string();
res.body.extend_from_slice(b"<h1>Not Found</h1>\r\n");
res.body.extend_from_slice(b"<h1>Not Found</h1>\n");
}
}
}
Expand Down Expand Up @@ -413,7 +404,7 @@ pub fn main(args: &[&str]) -> Result<(), ExitCode> {
delete(&req, &mut res)
}
_ => {
let s = b"<h1>Bad Request</h1>\r\n";
let s = b"<h1>Bad Request</h1>\n";
res.body.extend_from_slice(s);
res.code = 400;
res.mime = "text/html".to_string();
Expand Down Expand Up @@ -467,6 +458,7 @@ pub fn main(args: &[&str]) -> Result<(), ExitCode> {
fn content_type(path: &str) -> String {
let ext = path.rsplit_once('.').unwrap_or(("", "")).1;
match ext {
"bmp" => "image/bmp",
"css" => "text/css",
"csv" => "text/csv",
"gif" => "text/gif",
Expand Down

0 comments on commit 4af5cba

Please sign in to comment.