Skip to main content

std.net — URL

parse_url splits a URL into its components, url.* parses/builds and percent-encodes. No network request is made — it is pure string handling.

Usage

var u = std.net.parse_url("http://example.com:8080/path/to?q=1#frag")
print(u.scheme) // http
print(u.host) // example.com
print(u.port) // 8080 (number)
print(u.path) // /path/to?q=1#frag (path + query + fragment as one string)

var v = std.net.parse_url("ws://echo.example/socket")
print(v.scheme) // ws
print(v.host) // echo.example

var w = std.net.parse_url("https://example.com/")
print(w.port) // 443 — the default port when none is given

Return object

FieldTypeDescription
schemestring"http", "ws", etc.
hoststringHostname or IP
portintPort — the explicit one, or the scheme default (80 for http/ws, 443 for https/wss)
pathstringPath including ?query and #fragment

If the URL is malformed the call throws — handle it like any other error (see Errors). Parsing a wss:// URL also throws UNSUPPORTED on builds without OpenSSL.

The url sub-module

std.net.url adds finer-grained parsing, building, and encoding helpers:

FunctionPurpose
url.parse(s)Like parse_url but splits query and fragment into their own fields
url.encode(s)Percent-encode a string (encodeURIComponent behavior — unreserved chars pass through)
url.decode(s)Decode percent escapes; + is preserved literally
url.decode_form(s)Decode form data — + becomes space
url.build({scheme, host, port, path, query, fragment})Assemble a URL string; omits default ports (80/443) and empty components
var parts = std.net.url.parse("http://example.com/a?b=1&c=2#top")
print(parts.path) // /a
print(parts.query) // b=1&c=2
print(parts.fragment) // top

print(std.net.url.encode("a b&c")) // a%20b%26c
print(std.net.url.decode("a%20b%26c")) // a b&c
print(std.net.url.decode_form("a+b")) // a b ('+' is a space)
print(std.net.url.build({host: "example.com", path: "/x", query: "q=1"}))
// http://example.com/x?q=1

Tips

  • Use with HTTP Client to validate or rewrite URLs before request({url: ...}).
  • Combine with DNS if you need to resolve u.host manually, though clients normally resolve for you.

See also