URL.Data (URL v2.0.3)

Copy Markdown View Source

Parses the scheme-specific part of a data URL as defined in RFC 2397.

The payload is decoded during parsing: base64 payloads (those with the ;base64 parameter) are base64-decoded and all others are percent-decoded. The primary API is parse/1, which URL.new/1 calls for any URL with the data scheme.

Summary

Functions

Parses the path of a data URI into a t/0 struct.

Types

t()

@type t() :: %URL.Data{
  data: String.t() | {:error, String.t()},
  mediatype: binary(),
  params: map()
}

Functions

parse(uri)

@spec parse(URI.t()) :: {:ok, t()} | {:error, {module(), binary()}}

Parses the path of a data URI into a t/0 struct.

Arguments

  • uri is a URI.t/0 whose :scheme is "data".

Returns

  • {:ok, t:t/0} with the media type, parameters and decoded payload. The media type defaults to "text/plain". A base64 payload that cannot be decoded is returned as {:error, raw_payload} in the :data field, or

  • {:error, {URL.Parser.ParseError, reason}} if the path is not a valid data payload.

Examples

iex> data = URI.parse "data:text/plain;base64,SGVsbG8gV29ybGQh"
iex> URL.Data.parse(data)
{:ok,
 %URL.Data{
   mediatype: "text/plain",
   params: %{"encoding" => "base64"},
   data: "Hello World!"
 }}

iex> URL.Data.parse(URI.parse("data:,Hello%20World%21"))
{:ok, %URL.Data{mediatype: "text/plain", params: %{}, data: "Hello World!"}}

iex> URL.Data.parse(URI.parse("data:;base64"))
{:error,
 {URL.Parser.ParseError,
  "expected a comma. Detected on line 1 at \"\""}}