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)
|
63 68 | }
|
64 69 |
|
65 70 | /// Returns just the built query string.
|
66 71 | pub fn build_query(self) -> String {
|
67 72 | self.build_uri().query().unwrap_or_default().to_string()
|
68 73 | }
|
69 74 |
|
70 75 | /// Returns a full [`Uri`] with the query string updated.
|
71 76 | pub fn build_uri(self) -> Uri {
|
72 77 | let mut parts = self.base_uri.into_parts();
|
73 78 | parts.path_and_query = Some(
|
74 79 | self.new_path_and_query
|
75 80 | .parse()
|
76 81 | .expect("adding query should not invalidate URI"),
|
77 82 | );
|
78 83 | Uri::from_parts(parts).expect("a valid URL in should always produce a valid URL out")
|
79 84 | }
|
80 85 | }
|
81 86 |
|
82 87 | #[cfg(test)]
|
83 88 | mod test {
|
84 89 | use super::QueryWriter;
|
85 90 | use http_02x::Uri;
|
86 91 |
|
87 92 | #[test]
|
88 93 | fn empty_uri() {
|
89 94 | let uri = Uri::from_static("http://www.example.com");
|
90 95 | let mut query_writer = QueryWriter::new(&uri);
|
91 96 | query_writer.insert("key", "val%ue");
|
92 97 | query_writer.insert("another", "value");
|