diff options
Diffstat (limited to 'blog')
| -rw-r--r-- | blog/src/main.rs | 13 | ||||
| -rw-r--r-- | blog/src/querystring.rs | 50 |
2 files changed, 63 insertions, 0 deletions
diff --git a/blog/src/main.rs b/blog/src/main.rs index b0b8c71..ebae43a 100644 --- a/blog/src/main.rs +++ b/blog/src/main.rs @@ -2,10 +2,22 @@ use spider::http_server::{HttpHandler, HttpServer}; use spider::request::Request; use spider::response::Response; +mod querystring; +use crate::querystring::parse_qs; +use std::str; + struct MyHandler {} impl HttpHandler for MyHandler { fn do_get(&self, _request: Request) -> Response { + let params = str::from_utf8(&_request.body).unwrap().to_string(); + let params = parse_qs(params); + + println!("{}", _request.path); + for (key, val) in ¶ms { + println!(" {}={}", key, val); + } + return Response::html(String::from("hey"), 200); } @@ -18,6 +30,7 @@ impl MyHandler { pub fn new() -> MyHandler { return MyHandler {}; } + } // TODO(andrew): create logging package. diff --git a/blog/src/querystring.rs b/blog/src/querystring.rs new file mode 100644 index 0000000..8bb174a --- /dev/null +++ b/blog/src/querystring.rs @@ -0,0 +1,50 @@ +use std::str; +use std::collections::HashMap; +use std::num::ParseIntError; + + +pub fn parse_qs(query: String) -> HashMap<String, String> { + let query = percent_decode(query); + let mut map = HashMap::new(); + for pair in query.split('&') { + let pair = pair.split('=').collect::<Vec<&str>>(); + map.insert(pair[0].to_string(), pair[1].to_string()); + } + return map; +} + +fn percent_decode(s: String) -> String { + let len = s.len(); + let mut s = s.chars(); + let mut result = String::new(); + let mut decode = String::new(); + + let mut i = 0; + while i < len { + let cur = s.nth(0).unwrap(); + if cur == '%' { + decode.push(s.nth(0).unwrap()); + decode.push(s.nth(0).unwrap()); + i += 3; + continue; + } + if decode.len() != 0 { + match decode_hex(&decode) { + Ok(v) => result.push_str(str::from_utf8(&v).unwrap()), + Err(_) => () + }; + decode = String::new(); + } + + result.push(cur); + i += 1; + } + return result; +} + +fn decode_hex(s: &str) -> Result<Vec<u8>, ParseIntError> { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16)) + .collect() +} |