Skip to main content

rust_web_server/body/form_urlencoded/
mod.rs

1use std::collections::HashMap;
2use crate::symbol::SYMBOL;
3use crate::url::URL;
4
5/// Parser and serialiser for `application/x-www-form-urlencoded` bodies.
6pub struct FormUrlEncoded;
7
8impl FormUrlEncoded {
9    /// Parses a URL-encoded body into a `HashMap` of field name → value.
10    pub fn parse(data: Vec<u8>) -> Result<HashMap<String, String>, String> {
11        let boxed_string = String::from_utf8(data);
12        if boxed_string.is_err() {
13            let message = boxed_string.err().unwrap().to_string();
14            return Err(message)
15        }
16        let string = boxed_string.unwrap();
17        let string = string.replace(|x : char | x.is_ascii_control(), SYMBOL.empty_string).trim().to_string();
18
19
20        Ok(URL::parse_query(&string))
21    }
22
23    pub fn generate(map: HashMap<String, String>) -> String {
24        URL::build_query(map)
25    }
26}