Url.Parts
type Url.Parts = { scheme: string, opaque: string, user: string, host: string, port: string, path: string, query: string, fragment: string }Url.Parts is a URL reference divided as RFC 3986 does, with each absent part "". scheme is in lower case without its colon, opaque is what follows "scheme:" when that does not start with /, as in a mailto: address, and user is the userinfo as written. path and fragment are decoded, but path keeps %2F and %25 as written, while query is the raw text after the ?, for Url.parseQuery.
Details
- A part the reference does not have is
"", nevernull. pathandfragmentare decoded, butpathkeeps%2Fand%25as written.queryis raw: read its keys and values with Url.parseQuery.userholds the whole userinfo as written, a password included.- The fields are mutable, and a literal must give all eight. To change one part, parse the reference, set the field or spread it into a new literal, and write it back with Url.stringify.
Url.stringifyescapes every part butqueryandopaque, which it writes as they are; buildquerywith Url.stringifyQuery.
Basic examples
Url.parse divides a reference into a Url.Parts:
let parts = try Url.parse("https://ann@example.com:8080/docs/intro?lang=en#setup")
println(parts)Url.Parts{ scheme: "https", opaque: "", user: "ann", host: "example.com", port: "8080", path: "/docs/intro", query: "lang=en", fragment: "setup" }Read the parts you need as fields:
let parts = try Url.parse("https://example.com/search?q=ant")
println(parts.host)
println(parts.path)
println(parts.query)example.com
/search
q=antUrl.stringify turns the parts back into a reference:
let parts = try Url.parse("https://example.com/search?q=ant")
println(Url.stringify(parts))https://example.com/search?q=antScope
A relative reference has an empty scheme and host, and only the parts it writes:
let link = try Url.parse("../img/logo.png")
let search = try Url.parse("/search?page=2")
let anchor = try Url.parse("#intro")
println("${link.path} ${search.path} ${search.query} ${anchor.fragment}")
println(link.scheme.isEmpty() && link.host.isEmpty())../img/logo.png /search page=2 intro
trueA reference that starts with // has a host but no scheme:
let parts = try Url.parse("//cdn.example.com/lib.js")
println("[${parts.scheme}] [${parts.host}] [${parts.path}]")[] [cdn.example.com] [/lib.js]scheme is in lower case, without its colon:
println((try Url.parse("HTTPS://example.com")).scheme)httpsA reference whose content after scheme: does not start with /, as a mailto: address, keeps that content in opaque, and its path is empty:
let parts = try Url.parse("mailto:alice@example.com")
println(parts.scheme)
println(parts.opaque)
println(parts.path.isEmpty())mailto
alice@example.com
trueA single / after the colon starts the path, so the authority is empty, and so is host. Three slashes in a file: URL give the same parts:
let short = try Url.parse("file:/etc/hosts")
let long = try Url.parse("file:///etc/hosts")
println("[${short.host}] ${short.path}")
println(short == long)[] /etc/hosts
trueuser holds the userinfo as written, a password included, and port is the text after the colon:
let parts = try Url.parse("ftp://ann:s3cret@files.example.com:2121/pub")
println(parts.user)
println(parts.port)
println(parts.port.toInt())ann:s3cret
2121
2121path and fragment are decoded. query is the raw text after ?:
let parts = try Url.parse("https://example.com/my%20files/caf%C3%A9?q=a%20b#part%202")
println(parts.path)
println(parts.query)
println(parts.fragment)/my files/café
q=a%20b
part 2%2F and %25 stay escaped in path, so a slash inside a segment does not become a separator:
let parts = try Url.parse("/files/a%2Fb/100%25")
println(parts.path)
println(parts.path.split("/"))/files/a%2Fb/100%25
["", "files", "a%2Fb", "100%25"]Url.Parts is a record type, so a literal builds one, with every field given:
let parts = Url.Parts{
scheme: "https",
opaque: "",
user: "",
host: "example.com",
port: "",
path: "/a b",
query: "q=1",
fragment: "",
}
println(Url.stringify(parts))https://example.com/a%20b?q=1Applications
Change one part of a URL and keep the rest, with a spread:
func withHost(url: string, host: string): Result[string, Error] {
let parts = try Url.parse(url)
Result.ok(Url.stringify(Url.Parts{ ...parts, host }))
}
println(withHost("https://staging.example.com/api/v1?page=2", "example.com"))Ok{ value: "https://example.com/api/v1?page=2" }Set a field in place, here to drop the password before a URL goes into a log:
func redact(url: string): Result[string, Error] {
let parts = try Url.parse(url)
parts.user = parts.user.cut(":")?.before ?? parts.user
Result.ok(Url.stringify(parts))
}
println(redact("postgres://app:hunter2@db.internal:5432/orders"))
println(redact("https://example.com/"))Ok{ value: "postgres://app@db.internal:5432/orders" }
Ok{ value: "https://example.com/" }Read the query's keys and values with Url.parseQuery:
let parts = try Url.parse("https://shop.example.com/list?tag=new&tag=sale&q=red%20shoes")
let params = try Url.parseQuery(parts.query)
println(params["tag"])
println(params["q"])["new", "sale"]
["red shoes"]Add query parameters to a base URL, with Url.stringifyQuery building the query:
func withQuery(url: string, params: Map[string, Array[string]]): Result[string, Error] {
let parts = try Url.parse(url)
Result.ok(Url.stringify(Url.Parts{ ...parts, query: Url.stringifyQuery(params) }))
}
println(withQuery("https://example.com/search", Map{ "q": ["red shoes"], "page": ["2"] }))Ok{ value: "https://example.com/search?q=red+shoes&page=2" }Tell links that leave a site from those that stay:
func external(link: string, site: string): bool {
let parts = Url.parse(link)
if parts is Err { return false }
let { host } = parts.value
!host.isEmpty() && host != site
}
let links = ["/about", "https://example.com/blog", "https://other.org/", "#top", "mailto:hi@example.com"]
println(links | Array.filter({ external(x, "example.com") }))["https://other.org/"]Properties and relations
Url.stringify writes the parts as a reference that parses back to the same parts:
let urls = [
"https://ann@example.com:8080/a%2Fb/my%20docs?q=a%20b#top",
"mailto:alice@example.com",
"file:///etc/hosts",
"../img/logo.png",
"//cdn.example.com/lib.js",
]
for url in urls {
let parts = try Url.parse(url)
assert(try Url.parse(Url.stringify(parts)) == parts)
}Two Url.Parts are equal when every field is equal, so references that differ only in the case of the scheme parse to equal parts:
assert(try Url.parse("HTTP://example.com/") == try Url.parse("http://example.com/"))Possible issues
query is not decoded, unlike path and fragment. Decode its keys and values with Url.parseQuery:
let parts = try Url.parse("https://example.com/search?q=red%20shoes")
println(parts.query)
println((try Url.parseQuery(parts.query))["q"])q=red%20shoes
["red shoes"]Url.stringify writes query as it is, without escaping, so a space set there stays a bare space. Build query with Url.stringifyQuery:
let base = try Url.parse("https://example.com/search")
println(Url.stringify(Url.Parts{ ...base, query: "q=red shoes" }))
let query = Url.stringifyQuery(Map{ "q": ["red shoes"], "page": ["2"] })
println(Url.stringify(Url.Parts{ ...base, query }))https://example.com/search?q=red shoes
https://example.com/search?q=red+shoes&page=2A literal must give every field, even the empty ones:
let parts = Url.Parts{ scheme: "https", opaque: "", user: "", host: "example.com", path: "/" }
// error: Url.Parts literal is missing the field port
// error: Url.Parts literal is missing the field query
// error: Url.Parts literal is missing the field fragmentport is a string, and "" when the reference has none, not the scheme's default port:
let parts = try Url.parse("https://example.com/")
println(parts.port.isEmpty())
println(parts.port.toInt())true
nullA reference that is not well formed gives no Url.Parts, but an Err:
println(Url.parse("http://my host/"))
println(Url.parse("/100%"))Err{ error: Error{ message: "parse \"http://my host/\": invalid character \" \" in host name" } }
Err{ error: Error{ message: "parse \"/100%\": invalid URL escape \"%\"" } }See also
Url.parse · Url.stringify · Url.parseQuery · Url.stringifyQuery · Url.escape · Url.unescape
