parse out query string

pull/1/head
dvkt 4 years ago
parent 42f67a2c05
commit 056caa0dcb

@ -1,21 +1,25 @@
use crate::Result;
use std::fs;
/// This struct represents a single gopher request.
#[derive(Debug, Clone)]
pub struct Request {
pub selector: String,
pub query: String,
pub root: String,
pub host: String,
pub port: u16,
}
impl Request {
/// Try to create a new request state object.
pub fn from(host: &str, port: u16, root: &str) -> Result<Request> {
Ok(Request {
host: host.into(),
port: port,
root: fs::canonicalize(root)?.to_string_lossy().into(),
selector: String::new(),
query: String::new(),
})
}
@ -33,4 +37,20 @@ impl Request {
pub fn relative_file_path(&self) -> String {
self.file_path().replace(&self.root, "")
}
/// Set selector + query based on what the client sent.
pub fn parse_request(&mut self, line: &str) {
self.query.clear();
self.selector.clear();
if let Some(i) = line.find('\t') {
if line.len() >= i + 1 {
self.query.push_str(&line[i + 1..]);
self.selector.push_str(&line[..i]);
} else {
self.selector.push_str(&line[..i]);
}
} else {
self.selector.push_str(line);
}
}
}

@ -52,7 +52,7 @@ fn accept(stream: TcpStream, mut req: Request) -> Result<()> {
let mut lines = reader.lines();
if let Some(Ok(line)) = lines.next() {
println!("-> Client sent: {:?}", line);
req.selector = line;
req.parse_request(&line);
write_response(&stream, req)?;
}
Ok(())

Loading…
Cancel
Save