servo / rust-url

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

Question: How to convert `Host`/`Origin` to `URL`? #807

Closed JulianKnodt closed 1 year ago

JulianKnodt commented 1 year ago

I was wondering if there's anyway to convert from a Host back to a URL after calling url.host()? I realize this is probably under-specified, since there is no longer a scheme, so I was further wondering if there would be a. way to convert an Origin to a URL? After browsing through the docs & open GH issues, I didn't see any question about this, so was wondering if it made sense to add such a thing?

valenting commented 1 year ago

Not sure what you mean by converting back? You can always build a new URL. But maybe you want something else?

use url;
use url::Url;

fn main() {
    let url = Url::parse("http://hostname:123/").unwrap();
    println!("{:?}", url);
    let new_url = "https://".to_owned() + &url.host().unwrap().to_string();
    let new_url = Url::parse(&new_url).unwrap();
    println!("{:?}", new_url);
}

playground link

JulianKnodt commented 1 year ago

hmmmm specifically I'm thinking about the use case of converting https://www.foo.com/a/b/c/d to https://www.foo.com/. I reread the docs ad noticed I can do this with .path_segments_mut().clear(), but maybe it's worth adding an explicit note to path_segments_mut()?

The reason I asked this question is because I expected a method that explicitly drops all path segments, and I equated it in my mind with .host().

tmccombs commented 1 year ago

You would probably also want to clear the query string and fragment in that case.

valenting commented 1 year ago

Ah, I see. In that case you can probably also use the slicing like here. Be mindful if you also want it to have username and password.