检查URL在Elixir中是否有效 [英] Check if a URL is valid in elixir

查看:86
本文介绍了检查URL在Elixir中是否有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要检查给定的URL是否有效,理想情况下是否也可以解析该URL。

I want to check if a given URL is valid, ideally if the url resolves too.

首先,我将如何检查字符串的有效性(即regex)

Firstly, how would I go about just checking the string validity (i.e. regex)

其次,有没有一种方法可以查看URL是否真正解析为Internet上的资源?

and secondly, is there a way that I can see if the URL actually resolves to a resource on the internet?

谢谢

推荐答案

我不会使用regex,而是使用URI包以文本方式验证URI,然后检查主机名是否通过:inet.gethostbyname解析:

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:

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}

URI结构的主机字段。如果是相对资源,则为 nil 。如果缺少方案$ http:// ftp:// ,则该方案将为nil。路径也应该在此处( /),即使它只是网站的根路径。然后,您要验证的是其中是否为 nil ,如下所示:

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://, or ftp:// 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 are nil or not, something like this:

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/")

然后您可以将此有效 uri传递给:inet.gethostbyname / 1

You can then pass this "valid" uri to :inet.gethostbyname/1

iex(18)> :inet.gethostbyname(to_char_list a.host)
{:ok, {:hostent, 'google.com', [], :inet, 4, [{216, 58, 217, 46}]}}

如果由于某种原因而失败:inet.gethostbyname / 1 将返回 {:error,:nxdomain}

If for whatever reason this fails :inet.gethostbyname/1 will return {:error, :nxdomain}

这篇关于检查URL在Elixir中是否有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆