我想检查给定的URL是否有效,理想情况下,如果URL也解析了.
首先,我将如何检查字符串的有效性(即正则表达式)
其次,有没有办法让我看到网址是否真的解析为互联网上的资源?
谢谢
Yos*_*iki 20
我将使用URI包以文本方式验证URI,然后检查主机名是否通过以下方式解析:而不是伸出正则表达式:inet.gethostbyname:
iex(1)> URI.parse("http://google.com/")
%URI{authority: "google.com", fragment: nil, host: "google.com",
path: "/", port: 80, query: nil, scheme: "http", userinfo: nil}
Run Code Online (Sandbox Code Playgroud)
请注意URI结构的"host"字段.如果它是相对资源,那么这将是nil
.如果方案,即http://
,或ftp://
缺失,则另外的方案将是零.路径也应该在那里("/"),即使它只是站点的根路径.然后,您的验证是否是这些中的任何一个nil
,如下所示:
defmodule Validation do
def validate_uri(str) do
uri = URI.parse(str)
case uri do
%URI{scheme: nil} -> {:error, uri}
%URI{host: nil} -> {:error, uri}
%URI{path: nil} -> {:error, uri}
uri -> {:ok, uri}
end
end
end
{:ok, uri} = Validation.validate_uri("http://google.com/")
Run Code Online (Sandbox Code Playgroud)
然后,您可以将此"有效"uri传递给:inet.gethostbyname/1
iex(18)> :inet.gethostbyname(to_char_list a.host)
{:ok, {:hostent, 'google.com', [], :inet, 4, [{216, 58, 217, 46}]}}
Run Code Online (Sandbox Code Playgroud)
如果由于某种原因失败:inet.gethostbyname/1
将返回{:error, :nxdomain}