I want to check if a given URL is valid, ideally if the url resolves too.
Firstly, how would I go about just checking the string validity (i.e. regex)
and secondly, is there a way that I can see if the URL actually resolves to a resource on the internet?
Thanks
Instead of reaching out for a regex I would use the URI package to textually validate the URI, and then check if the host name resolves through :inet.gethostbyname:
Note the "host" field of the URI struct. If it's a relative resource then this will be
nil
. Additionally scheme will be nil if the scheme, i.e.http://
, orftp://
is missing. The path should also be there("/") even if it's just the root path of the site. Your validation then is whether any of these arenil
or not, something like this:You can then pass this "valid" uri to :inet.gethostbyname/1
If for whatever reason this fails
:inet.gethostbyname/1
will return{:error, :nxdomain}