Better file path handling and updated examples
parent
f8cde8ac14
commit
5e06f46739
Binary file not shown.
|
After Width: | Height: | Size: 109 KiB |
|
|
@ -1,4 +1,6 @@
|
|||
# Test
|
||||
+++
|
||||
title = "Test"
|
||||
+++
|
||||
|
||||
## Test2
|
||||
|
||||
|
|
|
|||
|
|
@ -1 +1,6 @@
|
|||
+++
|
||||
title = "Test 2"
|
||||
pics = ["pics/demo/demo.jpg"]
|
||||
+++
|
||||
|
||||
Something **new**
|
||||
|
|
|
|||
|
|
@ -16,9 +16,13 @@ impl ByteBuffer {
|
|||
self.buffer.len() - self.cursor
|
||||
}
|
||||
|
||||
pub fn write_usize(&mut self, value: usize) {
|
||||
self.write_bytes(&value.to_be_bytes());
|
||||
}
|
||||
|
||||
pub fn write_string(&mut self, value: &str) {
|
||||
let _ = self.buffer.write(&value.len().to_be_bytes());
|
||||
let _ = self.buffer.write(value.as_bytes());
|
||||
self.write_bytes(&value.len().to_be_bytes());
|
||||
self.write_bytes(value.as_bytes());
|
||||
}
|
||||
|
||||
pub fn write_bytes(&mut self, value: &[u8]) {
|
||||
|
|
|
|||
46
src/main.rs
46
src/main.rs
|
|
@ -1,7 +1,8 @@
|
|||
use std::{
|
||||
fs::read,
|
||||
fs,
|
||||
io::Write,
|
||||
net::{SocketAddr, TcpListener, TcpStream},
|
||||
path::Path,
|
||||
result,
|
||||
str::FromStr,
|
||||
};
|
||||
|
|
@ -30,25 +31,50 @@ fn main() -> Result<()> {
|
|||
}
|
||||
|
||||
fn handle_connection(mut conn: TcpStream) -> Result<()> {
|
||||
let files = ["examples/test.md", "examples/test2.md"];
|
||||
let export = "./examples/";
|
||||
|
||||
for file in files {
|
||||
let mut buffer = ByteBuffer::default();
|
||||
match read(format!("./{file}")) {
|
||||
let mut paths = vec![];
|
||||
let mut buffer = ByteBuffer::default();
|
||||
|
||||
visit_dir(export, &mut paths);
|
||||
|
||||
buffer.write_usize(paths.len());
|
||||
|
||||
for file in paths {
|
||||
let path = file.replace(export, "");
|
||||
buffer.write_string(&path);
|
||||
|
||||
match fs::read(format!("./{file}")) {
|
||||
Ok(data) => {
|
||||
buffer.write_string(file);
|
||||
buffer.write_usize(data.len());
|
||||
buffer.write_bytes(&data);
|
||||
|
||||
let _ = conn.write_all(&buffer);
|
||||
let _ = conn.flush();
|
||||
}
|
||||
Err(_) => eprintln!("No file found"),
|
||||
Err(_) => {
|
||||
buffer.write_usize(0);
|
||||
eprintln!("No file found")
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let _ = conn.write_all(&buffer);
|
||||
let _ = conn.flush();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn visit_dir<P: AsRef<Path>>(path: P, file_paths: &mut Vec<String>) {
|
||||
for entry in fs::read_dir(path).unwrap().flatten() {
|
||||
if entry.path().is_dir() {
|
||||
visit_dir(entry.path(), file_paths);
|
||||
return;
|
||||
}
|
||||
|
||||
let file_path = entry.path().to_str().unwrap().to_string();
|
||||
|
||||
file_paths.push(file_path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::Read;
|
||||
|
|
|
|||
Loading…
Reference in New Issue