ddn.net.uri¶
This page provides runnable examples for common URI/URL/URN tasks using the ddn.net.uri module.
1) Parse, inspect components, and serialize¶
#!/usr/bin/env dub
/+ dub.sdl:
name "net-uri-parse"
dependency "ddn" version="*"
+/
module examples.net_uri_parse;
import std.stdio : writeln;
import ddn.net.uri;
void main() {
auto u = URI.parse("http://user:pass@example.com:80/a/./b/../c?x=1#frag");
writeln("scheme = ", u.scheme);
writeln("authority= ", u.hasAuthority ? u.authority.toString() : "(none)");
writeln("path = ", u.path);
writeln("query = ", u.hasQueryComponent ? u.query : "(none)");
writeln("fragment = ", u.hasFragmentComponent ? u.fragment : "(none)");
writeln("as string= ", u.toString());
}
2) Normalize and resolve a relative reference (RFC 3986 §5.2)¶
#!/usr/bin/env dub
/+ dub.sdl:
name "net-uri-normalize-resolve"
dependency "ddn" version="*"
+/
module examples.net_uri_normalize_resolve;
import std.stdio : writeln;
import ddn.net.uri;
void main() {
auto u = URI.parse("HTTP://EXAMPLE.COM:80/%7Euser/./a/../b");
auto n = u.normalize();
writeln("normalized = ", n.toString());
// normalized = http://example.com/~user/b
auto base = URI.parse("http://a/b/c/d;p?q");
auto ref = URI.parse("g?y#s");
auto r = base.resolve(ref);
writeln("resolved = ", r.toString());
// resolved = http://a/b/c/g?y#s
}
3) Use URL and URN wrappers¶
#!/usr/bin/env dub
/+ dub.sdl:
name "net-uri-wrappers"
dependency "ddn" version="*"
+/
module examples.net_uri_wrappers;
import std.stdio : writeln;
import ddn.net.uri;
void main() {
auto url = URL.parse("https://user@example.com:443/path?x=1");
writeln("url.host = ", url.host);
writeln("url.port = ", url.port);
writeln("url = ", url.toString());
auto urn = URN.parse("urn:example:animal:ferret:nose");
writeln("urn.nss = ", urn.nss);
writeln("urn = ", urn.toString());
}
4) Percent-encoding, IDNA, and URI Templates¶
#!/usr/bin/env dub
/+ dub.sdl:
name "net-uri-encoding-idna-templates"
dependency "ddn" version="*"
+/
module examples.net_uri_encoding_idna_templates;
import std.stdio : writeln;
import ddn.net.uri;
void main() {
// Percent-encoding helpers
writeln(pctDecode("%41%42%43")); // ABC
writeln(pctNormalize("%7e", Component.Path)); // ~
writeln(pctEncode("€", Component.Path)); // %E2%82%AC
// IDNA: Unicode hostname -> ASCII (Punycode)
auto u = URI.parse("http://bücher.example/");
auto n = u.normalizeIDNA();
writeln(n.toString()); // http://xn--bcher-kva.example/
writeln(n.hostUnicode()); // bücher.example
// RFC 6570 URI Templates
auto t = UriTemplate.parse("http://example.com{/path}{?q}");
UriTemplateVars vars;
vars.set("path", UriTemplateValue.fromScalar("foo/bar"));
vars.set("q", UriTemplateValue.fromScalar("hello world"));
writeln(t.expand(vars));
// http://example.com/foo%2Fbar?q=hello%20world
}