url_query_string
url_query_string is a Rust procedural macro crate that simplifies converting structs into URL query strings. By deriving ToQueryString, two methods are automatically generated for your structs:
to_query_string: Converts the struct into a query string, returning aString. Ignores errors by returning an empty string if serialization fails.try_to_query_string: Converts the struct into a query string, returning aResult<String, serde_qs::Error>.
Features
- Easy Query String Generation: No manual string concatenation; works out of the box with your structs.
- Serde-Compatible: Fully integrates with
serde, allowing customization of query string formats. - Error Handling: Choose between ignoring errors or handling them explicitly.
Installation
Add the crate to your Cargo.toml:
[]
= "0.1"
= { = "1.0", = ["derive"] }
= "0.7"
Usage
Example
use Serialize;
use ToQueryString;
Output
Running the example above will produce:
Query String: page=1&pageSize=20&id=test_id&userId=user_123
Query String (with Result): page=1&pageSize=20&id=test_id&userId=user_123
Customization with serde
You can use serde attributes like #[serde(rename_all = "snake_case")] to control the format of your query strings:
This will generate query strings like:
user_name=test_user&access_token=abcd1234
Methods Generated
When deriving ToQueryString, the following methods are added to your struct:
to_query_string: Returns aStringwith the query string. Errors are ignored.try_to_query_string: Returns aResult<String, serde_qs::Error>for explicit error handling.
Contribution
Contributions are welcome! If you encounter any bugs or have feature requests, please open an issue or submit a pull request on GitHub.
License
This project is licensed under the MIT License. See the LICENSE file for details.