Browse Source

Fighting with find()

master
Noelle 4 years ago
parent
commit
128e16affb
2 changed files with 33 additions and 21 deletions
  1. 23
    6
      src/lib.rs
  2. 10
    15
      src/main.rs

+ 23
- 6
src/lib.rs View File

@@ -122,8 +122,8 @@ impl Response {
self.header = String::from(hdr);
}

pub fn get_header(&self) {
self.header
pub fn get_header(&self) -> &String {
&self.header
}

pub fn set_content(&mut self, cnt: &str) {
@@ -134,21 +134,38 @@ impl Response {
self.content.push_str(cnt);
}

pub fn get_content(&self) {
self.content
pub fn get_content(&self) -> &String {
&self.content
}
}

#[derive(Copy, Clone)]
pub struct Route {
path: &'static str,
action: fn(&&str, &mut Response),
}

impl Route {
fn new(p: String, a: fn(&&str, &mut Response)) {
pub fn new(p: &'static str, a: fn(&&str, &mut Response)) -> Route {
Route {
path: p,
action: (a),
action: a,
}
}

pub fn set_path(&mut self, p: &'static str) {
self.path = p;
}

pub fn get_path(&mut self) -> &'static str {
&self.path
}

pub fn set_action(&mut self, a: fn(&&str, &mut Response)) {
self.action = a;
}

pub fn get_action(&mut self) -> fn(&&str, &mut Response) {
self.action
}
}

+ 10
- 15
src/main.rs View File

@@ -59,7 +59,7 @@ fn handle_connection(mut stream: TcpStream) {
}
// println!("Sending {}: {}", r.header, r.path);
let response = format!("{}{}", r.header, r.content);
let response = format!("{}{}", r.get_header(), r.get_content());

stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
@@ -69,22 +69,16 @@ fn handle_connection(mut stream: TcpStream) {
// println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
}

fn response_add_file(p: &str, mut r: &mut Response) {
r.set_content(fs::read_to_string(p).unwrap());
fn response_add_file(p: &str, r: &mut Response) {
r.set_content(fs::read_to_string(p).unwrap().as_str());
}

fn route(c: &str, mut r: &mut Response) {

let routes = vec![
Route {
path: "api/hi",
action: hi,
},
Route {
path: "api/bye",
action: bye,
},
];
let mut routes = vec![];
routes.push(Route::new("api/hi", hi));
routes.push(Route::new("api/bye", bye));


// println!("Asked to fetch {}", c);
@@ -94,10 +88,11 @@ fn route(c: &str, mut r: &mut Response) {
r.set_header("HTTP/1.1 200 OK\r\n\r\n");
response_add_file("index.html", &mut r);
} else if c.starts_with("api/") {
let valid_route = routes.iter().find(|&x| x.path == c);
let mut iter_routes = routes.into_iter();
let valid_route = iter_routes.find(|&&x| x.get_path() == c);
match valid_route {
Some(rt) => {
(rt.action)(&c, &mut r);
(rt.get_action())(&c, &mut r);
},
None => {
none_api(&c, &mut r);

Loading…
Cancel
Save