Packages

Utility functions to deal with Top-Level Domains of the global DNS system. Fetches the current list of TLDs from IANA and makes it accessible with a simple function, and offers minor utilties for recognising TLDs in domain names.

Current section

Files

Jump to
tld lib tld.ex
Raw

lib/tld.ex

defmodule Tld do
@moduledoc """
Top-Level Domain module for BEAM.
Lets you get the current list of TLDs, as well as find the TLD in a domain name.
"""
@moduledoc since: "0.1.0"
alias Tld.DomainName
alias Tld.ListServer
@doc """
Get list of all Top-Level Domains.
## Examples
iex> list = Tld.get_list()
iex> Enum.member?(list, "NET")
true
iex> Enum.member?(list, "TEST")
false
"""
@doc since: "0.1.0"
def get_list do
ListServer.get_list()
end
@doc """
If input string contains a domain name, get its TLD.
Returns {:ok, "COM"} if found (COM being replaced with the actual TLD found),
{:err, :not_found} if TLD was not found in string, and {:err, :invalid_input}
if not given a string.
## Examples
iex> Tld.get_tld_from_domain_name("contoso.com")
{:ok, "COM"}
iex> Tld.get_tld_from_domain_name("FACE.BORG.TEST")
{:err, :not_found}
iex> Tld.get_tld_from_domain_name("CORRUPT.GOV")
{:ok, "GOV"}
iex> Tld.get_tld_from_domain_name('NOTASTRING.NET')
{:err, :invalid_input}
iex> Tld.get_tld_from_domain_name(42)
{:err, :invalid_input}
iex> Tld.get_tld_from_domain_name(nil)
{:err, :invalid_input}
"""
@doc since: "0.1.0"
def get_tld_from_domain_name(""), do: {:err, :not_found}
def get_tld_from_domain_name(name) when is_binary(name) do
match =
name
# Domain names are case-insensitive, but our matching logic is not, so
# upcase the candidate string before matching.
|> String.upcase()
|> DomainName.match_tld(get_list())
if is_binary(match) do
{:ok, match}
else
{:err, :not_found}
end
end
def get_tld_from_domain_name(_), do: {:err, :invalid_input}
@doc """
Simple check if string is a valid TLD.
Returns true if given a valid TLD ("COM", "dk", etc.)
## Examples
iex> Tld.is_tld?("COM")
true
iex> Tld.is_tld?("dk")
true
iex> Tld.is_tld?("amazing.ch")
false
iex> Tld.is_tld?(" NET")
false
iex> Tld.is_tld?("ORG ")
false
iex> Tld.is_tld?("")
false
iex> Tld.is_tld?(42)
false
iex> Tld.is_tld?(nil)
false
"""
@doc since: "0.2.0"
def is_tld?(input) when is_binary(input) and byte_size(input) > 0 do
Enum.member?(get_list(), String.upcase(input))
end
def is_tld?(_whatever), do: false
end