From cbcb4d8c9fc1ec276e6b67abb7ee5de3b3ac0fbb Mon Sep 17 00:00:00 2001 From: Bryan Newbold Date: Tue, 25 Aug 2020 13:24:51 -0700 Subject: improve query param parsing --- src/lib.rs | 40 ++-------------------------------------- 1 file changed, 2 insertions(+), 38 deletions(-) (limited to 'src') diff --git a/src/lib.rs b/src/lib.rs index ffc06bd..00b7b38 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -56,7 +56,7 @@ pub async fn filter_request(req: Request, config: &ProxyConfig) -> Result< return Err(ProxyError::NotSupported("only request paths with up to three segments allowed".to_string())) } - let params = parse_params(parts.uri.query())?; + let params: UrlQueryParams = serde_urlencoded::from_str(parts.uri.query().unwrap_or("")).unwrap(); // this is sort of like a router let body = match (&parts.method, path_chunks.as_slice()) { @@ -81,7 +81,7 @@ pub async fn filter_request(req: Request, config: &ProxyConfig) -> Result< _ => Err(ProxyError::NotSupported("unknown endpoint".to_string()))?, }; - let upstream_query = serialize_params(¶ms); + let upstream_query = serde_urlencoded::to_string(params).unwrap(); let upstream_query_and_params = if upstream_query.len() > 0 { format!("{}?{}", req_path, upstream_query) } else { @@ -129,39 +129,3 @@ pub fn filter_search_request(index: &str, _params: &UrlQueryParams, body: &[u8], Ok(Body::empty()) } } - -pub fn parse_params(query: Option<&str>) -> Result { - println!("params: {:?}", query); - let raw_params: serde_json::map::Map = query - .map(|q| { - url::form_urlencoded::parse(q.as_bytes()) - .into_owned() - .map(|(k,v)| (k, serde_json::from_str(&v).unwrap())) - .collect() - }) - .unwrap_or_else(serde_json::map::Map::new); - let parsed: UrlQueryParams = serde_json::from_value(serde_json::Value::Object(raw_params)).unwrap(); - Ok(parsed) -} - -pub fn serialize_params(params: &UrlQueryParams) -> String { - - let json_value = serde_json::to_value(params).unwrap(); - let value_map: serde_json::map::Map = match json_value { - serde_json::Value::Object(val) => val, - _ => panic!("expected an object"), - }; - - let mut builder = url::form_urlencoded::Serializer::new(String::new()); - // XXX: array and object types should raise an error? - for (k, v) in value_map.iter() { - match v { - serde_json::Value::Null | serde_json::Value::Object(_) | serde_json::Value::Array(_) => (), - serde_json::Value::Bool(_) | serde_json::Value::Number(_) | serde_json::Value::String(_) => { - let string_val = serde_json::to_string(&v).unwrap(); - builder.append_pair(k, &string_val); - } - } - } - builder.finish() -} -- cgit v1.2.3