45 45 | pub fn clear_params(&mut self) {
|
46 46 | if let Some(index) = self.new_path_and_query.find('?') {
|
47 47 | self.new_path_and_query.truncate(index);
|
48 48 | self.prefix = Some('?');
|
49 49 | }
|
50 50 | }
|
51 51 |
|
52 52 | /// Inserts a new query parameter. The key and value are percent encoded
|
53 53 | /// by `QueryWriter`. Passing in percent encoded values will result in double encoding.
|
54 54 | pub fn insert(&mut self, k: &str, v: &str) {
|
55 + | self.insert_encoded(&percent_encode_query(k), &percent_encode_query(v));
|
56 + | }
|
57 + |
|
58 + | /// Inserts a new already encoded query parameter. The key and value will be inserted
|
59 + | /// as is.
|
60 + | pub fn insert_encoded(&mut self, encoded_k: &str, encoded_v: &str) {
|
55 61 | if let Some(prefix) = self.prefix {
|
56 62 | self.new_path_and_query.push(prefix);
|
57 63 | }
|
58 64 | self.prefix = Some('&');
|
59 - | self.new_path_and_query.push_str(&percent_encode_query(k));
|
65 + | self.new_path_and_query.push_str(encoded_k);
|
60 66 | self.new_path_and_query.push('=');
|
61 - |
|
62 - | self.new_path_and_query.push_str(&percent_encode_query(v));
|
67 + | self.new_path_and_query.push_str(encoded_v)
|
68 + |
|
63 69 | }
|
64 70 |
|
65 71 | /// Returns just the built query string.
|
66 72 | pub fn build_query(self) -> String {
|
67 73 | self.build_uri().query().unwrap_or_default().to_string()
|
68 74 | }
|
69 75 |
|
70 76 | /// Returns a full [`Uri`] with the query string updated.
|
71 77 | pub fn build_uri(self) -> Uri {
|
72 78 | let mut parts = self.base_uri.into_parts();
|
73 79 | parts.path_and_query = Some(
|
74 80 | self.new_path_and_query
|
75 81 | .parse()
|
76 82 | .expect("adding query should not invalidate URI"),
|
77 83 | );
|
78 84 | Uri::from_parts(parts).expect("a valid URL in should always produce a valid URL out")
|
79 85 | }
|
80 86 | }
|
81 87 |
|
82 88 | #[cfg(test)]
|
83 89 | mod test {
|
84 90 | use super::QueryWriter;
|
85 91 | use http_02x::Uri;
|
86 92 |
|
87 93 | #[test]
|
88 94 | fn empty_uri() {
|
89 95 | let uri = Uri::from_static("http://www.example.com");
|
90 96 | let mut query_writer = QueryWriter::new(&uri);
|
91 97 | query_writer.insert("key", "val%ue");
|
92 98 | query_writer.insert("another", "value");
|