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:
We use the built-in
Uri
class to parse URLs, which is part of thedart:core
library.The
Uri.parse()
method is used to parse the URL string into aUri
object.Dart’s
Uri
class provides properties likescheme
,userInfo
,host
,port
,path
,fragment
,query
, andqueryParameters
to access different parts of the URL.For the user information, we need to manually split the
userInfo
string to get the username and password separately.The
queryParameters
property provides the query parameters as aMap<String, String>
, which is more convenient than Go’surl.Values
(which is amap[string][]string
).Dart doesn’t have a direct equivalent to Go’s
net.SplitHostPort()
, but theUri
class provideshost
,hostname
, andport
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.