Url Parsing in Dart

import 'dart:io';
import 'package:http/http.dart' as http;

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

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

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

  // `userInfo` contains all authentication info; we need to split it
  // to get individual username and password.
  print(u.userInfo);
  var userInfoParts = u.userInfo.split(':');
  print(userInfoParts[0]); // username
  print(userInfoParts[1]); // password

  // The `host` contains both the hostname and the port,
  // if present. `port` is available separately.
  print(u.host);
  print(u.hostname);
  print(u.port);

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

  // To get query params in a string of `k=v` format,
  // use `query`. You can also access query params
  // as a map using `queryParameters`.
  print(u.query);
  print(u.queryParameters);
  print(u.queryParameters['k']);
}

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

$ dart run url_parsing.dart
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
{k: v}
v

In this Dart version:

  1. We use the built-in Uri class to parse URLs, which is part of the dart:core library.

  2. The Uri.parse() method is used to parse the URL string into a Uri object.

  3. Dart’s Uri class provides properties like scheme, userInfo, host, port, path, fragment, query, and queryParameters to access different parts of the URL.

  4. For the user information, we need to manually split the userInfo string to get the username and password separately.

  5. The queryParameters property provides the query parameters as a Map<String, String>, which is more convenient than Go’s url.Values (which is a map[string][]string).

  6. Dart doesn’t have a direct equivalent to Go’s net.SplitHostPort(), but the Uri class provides host, hostname, and port properties separately.

This example demonstrates how to parse and extract information from URLs in Dart, which is a common task in web and network programming.