-module(url_parsing).
-export([main/0]).
main() ->
% We'll parse this example URL, which includes a
% scheme, authentication info, host, port, path,
% query params, and query fragment.
S = "postgres://user:pass@host.com:5432/path?k=v#f",
% Parse the URL and ensure there are no errors.
{ok, U} = uri_string:parse(S),
% Accessing the scheme is straightforward.
io:format("~p~n", [maps:get(scheme, U)]),
% UserInfo contains all authentication info; we need to parse it further
% to get individual username and password values.
UserInfo = maps:get(userinfo, U),
[Username, Password] = string:split(UserInfo, ":"),
io:format("~p~n", [UserInfo]),
io:format("~p~n", [Username]),
io:format("~p~n", [Password]),
% The Host contains both the hostname and the port,
% if present. We can extract them separately.
Host = maps:get(host, U),
Port = maps:get(port, U),
io:format("~p:~p~n", [Host, Port]),
io:format("~p~n", [Host]),
io:format("~p~n", [Port]),
% Here we extract the path and the fragment after the #.
io:format("~p~n", [maps:get(path, U)]),
io:format("~p~n", [maps:get(fragment, U)]),
% To get query params in a string of k=v format,
% use the query field. You can also parse query params
% into a map using uri_string:dissect_query/1.
Query = maps:get(query, U),
io:format("~p~n", [Query]),
QueryMap = uri_string:dissect_query(Query),
io:format("~p~n", [QueryMap]),
io:format("~p~n", [proplists:get_value("k", QueryMap)]).