Url Parsing in D Programming Language

Our URL parsing program demonstrates how to parse and extract information from URLs in D. Here’s the full source code:

import std.stdio;
import std.net.curl;
import std.conv;
import std.uri;

void main()
{
    // We'll parse this example URL, which includes a
    // scheme, authentication info, host, port, path,
    // query params, and query fragment.
    string s = "postgres://user:pass@host.com:5432/path?k=v#f";

    // Parse the URL and ensure there are no errors.
    auto u = URL(s);

    // Accessing the scheme is straightforward.
    writeln(u.scheme);

    // User contains all authentication info; we can access
    // username and password separately.
    writeln(u.user);
    writeln(u.username);
    writeln(u.password);

    // The Host contains both the hostname and the port,
    // if present. We can access them separately.
    writeln(u.host);
    writeln(u.hostname);
    writeln(u.port);

    // Here we extract the path and the fragment after
    // the #.
    writeln(u.path);
    writeln(u.fragment);

    // To get query params in a string of k=v format,
    // use query. You can also parse query params
    // into an associative array.
    writeln(u.query);
    auto m = u.queryParams;
    writeln(m);
    writeln(m["k"]);
}

Running our URL parsing program shows all the different pieces that we extracted:

$ rdmd url_parsing.d
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
["k":"v"]
v

In this D version:

  1. We use the std.net.curl.URL struct to parse the URL.
  2. The URL struct provides properties like scheme, user, username, password, host, hostname, port, path, fragment, and query.
  3. We use queryParams to get an associative array of query parameters.
  4. D’s standard library provides similar functionality to Go’s net/url package, making the translation straightforward.

Note that D’s URL parsing capabilities are somewhat different from Go’s, but they cover the same basic functionality.