Detect URL or path

#1

I am creating a CLI tool that can take either a URL or a path as its argument. How do I detect whether a string is a URL or a path?

I am specifically talking about detecting absolute URLs like: https://users.rust-lang.org/
Versus paths like: /usr/local/bin/rustc or foo/bar/ok.rs or ../foo/bar/../ok.rs

I was thinking of using the url crate which has a function Url::parse that only parses absolute URLs and then defaulting to a path if that returns ParseError::RelativeUrlWithoutBase. Is there a better/more lightweight way to do this? I know URL parsing can be tricky so I am defaulting to not doing it myself.

#2

If you restrict the URLs to a couple of schemas, then simply check if a valid one is given as the start in the string and simply assume a file scheme is no scheme is provided.

2 Likes