gleam/uri

Utilities for working with URIs

This module provides functions for working with URIs (for example, parsing URIs or encoding query strings). The functions in this module are implemented according to RFC 3986.

Query encoding (Form encoding) is defined in the w3c specification. https://www.w3.org/TR/html52/sec-forms.html#urlencoded-form-data

Types

Type representing holding the parsed components of an URI. All components of a URI are optional, except the path.

pub type Uri {
  Uri(
    scheme: Option(String),
    userinfo: Option(String),
    host: Option(String),
    port: Option(Int),
    path: String,
    query: Option(String),
    fragment: Option(String),
  )
}

Constructors

  • Uri( scheme: Option(String), userinfo: Option(String), host: Option(String), port: Option(Int), path: String, query: Option(String), fragment: Option(String), )

Functions

pub external fn erl_parse(String) -> Dynamic
pub fn merge(base: Uri, relative: Uri) -> Result(Uri, Nil)

Resolve a uri with respect to the given base uri

The base uri must be an absolute uri or this function will return an error. The algorithm for merging uris is described in RFC 3986

pub fn origin(uri: Uri) -> Result(String, Nil)

Fetch the origin of a uri

Return the origin of a uri as defined in https://tools.ietf.org/html/rfc6454

The supported uri schemes are http and https Urls without a scheme will return Error

pub fn parse(string: String) -> Result(Uri, Nil)

Parses a compliant URI string into the Uri Type. If the string is not a valid URI string then an error is returned.

The opposite operation is uri.to_string

pub fn parse_query(
  query: String,
) -> Result(List(tuple(String, String)), Nil)

Parses an urlencoded query string into a list of key value pairs. Returns an error for invalid encoding.

The opposite operation is uri.query_to_string.

pub fn path_segments(path: String) -> List(String)

Split the path section of a URI into it's constituent segments.

Removes empty segments and resolves dot-segments as specified in section 5.2 of the RFC.

pub fn percent_decode(value: String) -> Result(String, Nil)

Decode a percent encoded string.

Example

percent_decode("100%25+great")

Ok("100% great")

pub fn percent_encode(value: String) -> String

Encode a string into a percent encoded representation. Note that this encodes space as +.

Example

percent_encode("100% great")

"100%25+great"

pub fn query_to_string(
  query: List(tuple(String, String)),
) -> String

Encode a list of key value pairs as a URI query string.

The opposite operation is uri.parse_query.

pub fn to_string(uri: Uri) -> String

Encode a Uri value as a URI string.

The opposite operation is uri.parse.