stage 7 attempt 4 (compatibility with previous tests)
This commit is contained in:
parent
4a298c8b1e
commit
f4b8eb502d
28
src/main.rs
28
src/main.rs
@ -14,15 +14,19 @@ use utils::*;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Args {
|
||||
pub directory: PathBuf,
|
||||
pub directory: Option<PathBuf>,
|
||||
}
|
||||
|
||||
type A = Arc<Args>;
|
||||
|
||||
|
||||
fn parse_args () -> Args {
|
||||
let directory = std::env::args().position(|e| e == "--directory").unwrap() + 1;
|
||||
let directory = PathBuf::from(std::env::args().nth(directory).unwrap());
|
||||
let directory = std::env::args()
|
||||
.position(|e| e == "--directory")
|
||||
.map(|e| e + 1)
|
||||
.map(|d| std::env::args().nth(d))
|
||||
.flatten()
|
||||
.map(|d| PathBuf::from(d));
|
||||
|
||||
Args {
|
||||
directory
|
||||
@ -68,13 +72,17 @@ async fn process (mut stream: TcpStream, args: A) -> Result<()> {
|
||||
// p if let Some(echo) = p.strip_prefix("/echo/") => Response::TextPlain(echo), // a nicer way to do that, not available in stable yet
|
||||
p if p.starts_with("/echo/") => Response::TextPlain(p.trim_start_matches("/echo/").to_owned()),
|
||||
p if p.starts_with("/files/") => {
|
||||
let path = args.directory.join(p.trim_start_matches("/files/"));
|
||||
let mut buf = vec![];
|
||||
if let Ok(mut f) = File::open(path).await {
|
||||
let _ = f.read_to_end(&mut buf).await;
|
||||
Response::OctetStream(buf)
|
||||
if let Some(path) = &args.directory {
|
||||
let path = path.join(p.trim_start_matches("/files/"));
|
||||
let mut buf = vec![];
|
||||
if let Ok(mut f) = File::open(path).await {
|
||||
let _ = f.read_to_end(&mut buf).await;
|
||||
Response::OctetStream(buf)
|
||||
} else {
|
||||
Response::_404
|
||||
}
|
||||
} else {
|
||||
Response::_404
|
||||
Response::_500
|
||||
}
|
||||
},
|
||||
_ => Response::_404,
|
||||
@ -113,6 +121,7 @@ impl Headers {
|
||||
#[derive(Debug, Clone)]
|
||||
enum Response {
|
||||
_404,
|
||||
_500,
|
||||
Empty,
|
||||
TextPlain (String),
|
||||
OctetStream (Vec<u8>)
|
||||
@ -127,6 +136,7 @@ impl Response {
|
||||
|
||||
let code = match self {
|
||||
Self::_404 => "404 Not Found",
|
||||
Self::_500 => "500 Internal Server Error",
|
||||
_ => "200 OK",
|
||||
};
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user