url
URLs (RFC 3986) with a host, in pure Louise: parse one, resolve a link
against it, write it back, and get the request target an HTTP client sends.
packages/fetch builds on it (ADR 0079).
import url.{type Url, Url}
url.parse "https://Example.com:8443/a/b?x=1#top"
// Ok(Url("https", "example.com", Some(8443), "/a/b", Some("x=1"), Some("top")))
use page <- result.try (url.parse "https://example.com/blog/post")
url.resolve page "../about" // Ok: https://example.com/about
url.resolve page "//cdn.example/i.png" // Ok: https://cdn.example/i.png
url.request_target page // "/blog/post"
url.port_or_default page // Some(443)
url.to_string page // "https://example.com/blog/post"
The type
pub type Url
{ Url(scheme: String, host: String, port: Option<Int>, path: String,
query: Option<String>, fragment: Option<String>) }
- The scheme and the host are lowercased. An IPv6 host keeps its brackets
(
"[::1]"), soto_stringand aHostheader can use it as it is. portisNonewhen the URL names none;port_or_defaultgives 80 forhttp/ws, 443 forhttps/wss,Nonefor another scheme.queryandfragmentareNonewhen absent andSome("")after a bare?or#.- The path is
""or starts with/, with its.and..segments removed. Percent escapes are kept as written: nothing is decoded. parse (to_string u) == Ok(u)for a parsedu.
What is refused
parse and resolve answer Error(reason) for:
- text with no scheme, or no
//hostafter it (mailto:,urn:,http:g): this package only represents URLs with a host; - a user name or password (
https://user:pass@host/), which a link should never carry and which hides the real host from a reader; - a host that is not ASCII. There is no IDNA (punycode) here: write the
xn--form; - a host with a character outside
A-Z a-z 0-9 - . _ ~(no percent escapes, no sub-delimiters), or an empty one; - a port that is not 0 to 65535;
- a control character anywhere (a CR or LF cannot reach a request line).
Resolving
resolve base reference is RFC 3986's §5.2, with remove_dot_segments.
It is tested against every example of §5.4.1 and §5.4.2, except the two
whose result has no host (g:h and the strict http:g), which are
refused.
The request target
request_target url is the path (/ when empty) and ?query, without the
fragment. A byte that cannot appear there as it is — a space, ", <,
\, a byte of a non-ASCII character, a % not followed by two hex
digits — is percent-encoded; escapes already written are kept. A Url
built by hand with a CR or LF in its path still gives a single line.