servo / rust-url

URL parser for Rust
https://docs.rs/url/
Apache License 2.0
1.27k stars 318 forks source link

Feature Proposal: Builder for Constructing New URL Instances from Parts #835

Open rectangular-zone opened 1 year ago

rectangular-zone commented 1 year ago

I work with databases; a use case I often have isn't parsing a URL, but rather constructing one from pieces -- provide my own host or IP address, set a scheme, add query params one at a time or many at once, etc etc. The current API starts from an assumption of parsing an existing URL from a string, then modifying it. I'd like to propose a wrapper for constructing a new URL.

Personally, I quite like a builder for this kind of thing. I'm imagining something a little like:

let maybe_url = UrlBuilder::new()
                    .with_scheme("postgresql")
                    .with_host("10.40.0.9")
                    .with_port(5432)
                    .with_subresource("application_db")
                    .build();

match maybe_url {
  Ok(url) => printlin!("Got: {}", url),                                     // -> Got: postgresql://10.40.0.9:5432/application_db
  Err(e) => eprintln!("Url construction failed: {}", e),   
}

Convenience methods for common patterns can be provided: with_https, for instance; an API like with_http_defaults could pre-set scheme and port.

I'm happy to contribute this if it sounds like a feature y'all would like to have!

dbrgn commented 1 year ago

This would be very welcome. The Uri type in the http crate contains a builder as well: https://docs.rs/http/latest/http/uri/struct.Uri.html

ajayd-san commented 1 year ago

hey, is this open? I'd gladly take this up .