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 fn merge(base: Uri, relative: Uri) -> Result(Uri, Nil)
Resolves 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)
Fetches the origin of a URI.
Returns 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
.
Examples
> assert Ok(uri) = parse("http://example.com/path?foo#bar")
> origin(uri)
Ok("http://example.com")
pub fn parse(uri_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
Examples
> parse("https://example.com:1234/a/b?query=true#fragment")
Ok(Uri(scheme: Some("https"), ...))
pub fn parse_query(query: String) -> Result(
List(#(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
.
Examples
> parse_query("a=1&b=2")
Ok([#("a", "1"), #("b", "2")])
pub fn path_segments(path: String) -> List(String)
Splits 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.
Examples
> path_segments("/users/1")
["users" ,"1"]
pub fn percent_decode(value: String) -> Result(String, Nil)
Decodes a percent encoded string.
Examples
> percent_decode("100%25+great")
Ok("100% great")
pub fn percent_encode(value: String) -> String
Encodes a string into a percent encoded representation.
Examples
> percent_encode("100% great")
"100%25%20great"
pub fn query_to_string(query: List(#(String, String))) -> String
Encodes a list of key value pairs as a URI query string.
The opposite operation is uri.parse_query
.
Examples
> query_to_string([#("a", "1"), #("b", "2")])
"a=1&b=2"