ExUtils.URLs (ExUtils v1.0.1)

Copy Markdown View Source

Elixir utility functions to work with URLs and URI structs.

Summary

Types

t()

A valid URI string

Functions

Extracts one or more valid HTTP/HTTPS URLs from a string.

Merges given query params to a URL's existing query params.

Normalizes a URL's percent encoding.

Checks if a string is a valid HTTP/HTTPS URL or not.

Types

t()

@type t() :: String.t()

A valid URI string

Functions

extract(string)

@spec extract(String.t()) :: [t()]

Extracts one or more valid HTTP/HTTPS URLs from a string.

Examples

iex> extract("something https://google.com other http://example.com/some/path?query=1#fragment test...")
["https://google.com", "http://example.com/some/path?query=1#fragment"]

iex> extract("API: https://api.example.com:4000/v1 and website: https://www.example.com")
["https://api.example.com:4000/v1", "https://www.example.com"]

iex> extract("")
[]

iex> extract("example.com and ftp://example.com")
[]

merge_query(url, params)

@spec merge_query(t(), Enumerable.t()) :: t()

Merges given query params to a URL's existing query params.

Examples

iex> merge_query("example.com", [])
"example.com"

iex> merge_query("/some/path?id=5", id: 10, view: "details")
"/some/path?id=10&view=details"

iex> merge_query("https://app.com/path/?a=1", %{"a" => 0, "b" => "hello"})
"https://app.com/path/?a=0&b=hello"

normalize_encoding(url)

@spec normalize_encoding(t()) :: t()

Normalizes a URL's percent encoding.

Already encoded characters are not double-encoded.

Examples

iex> normalize_encoding("/search results?q=hello world")
"/search%20results?q=hello%20world"

iex> normalize_encoding("/café/menu")
"/caf%C3%A9/menu"

iex> normalize_encoding(~s'/files/{draft}|notes"')
"/files/%7Bdraft%7D%7Cnotes%22"

iex> normalize_encoding("https://example.com/some%2Fpath")
"https://example.com/some/path"

valid?(url)

@spec valid?(t()) :: boolean()

Checks if a string is a valid HTTP/HTTPS URL or not.

Examples

iex> valid?("https://example.com/path?view=details#results")
true

iex> valid?("http://localhost:4000")
true

iex> valid?("google.com")
false

iex> valid?("Visit https://example.com")
false