Url Parsing in Ada

Our program will demonstrate how to parse URLs in Ada. URLs provide a uniform way to locate resources.

with Ada.Text_IO; use Ada.Text_IO;
with GNAT.Regpat; use GNAT.Regpat;

procedure URL_Parsing is
   URL : constant String := "postgres://user:pass@host.com:5432/path?k=v#f";
   
   -- Regular expression to parse URL components
   URL_Pattern : constant String := 
     "^([\w+]+)://([^:]+):([^@]+)@([^:/]+):(\d+)(/[^?#]*)(\?[^#]*)?(#.*)?";
   
   Matches : Match_Array (0 .. 8);
   
   procedure Print_Match (Index : Natural; Name : String) is
   begin
      if Matches (Index) /= No_Match then
         Put_Line (Name & ": " & URL (Matches (Index).First .. Matches (Index).Last));
      end if;
   end Print_Match;

begin
   -- Parse the URL using regular expression
   Match (URL_Pattern, URL, Matches);

   if Matches (0) = No_Match then
      Put_Line ("Invalid URL format");
      return;
   end if;

   -- Print parsed components
   Print_Match (1, "Scheme");
   Print_Match (2, "Username");
   Print_Match (3, "Password");
   Print_Match (4, "Host");
   Print_Match (5, "Port");
   Print_Match (6, "Path");
   Print_Match (7, "Query");
   Print_Match (8, "Fragment");
end URL_Parsing;

This Ada program uses regular expressions to parse the URL, as Ada doesn’t have a built-in URL parsing library like Go’s net/url. Here’s a breakdown of what the program does:

  1. We define a sample URL string containing various components.

  2. A regular expression pattern is defined to match and capture different parts of the URL.

  3. We use GNAT’s GNAT.Regpat package to perform the regular expression matching.

  4. The Print_Match procedure is a helper to print each matched component.

  5. In the main part of the program, we perform the regex match and then print each component if it was successfully matched.

This approach doesn’t provide the same level of robustness as Go’s url.Parse, but it demonstrates how you might approach URL parsing in Ada.

To run this program, save it as url_parsing.adb and compile it using the GNAT compiler:

$ gnatmake url_parsing.adb
$ ./url_parsing

The output will show the different components of the parsed URL:

Scheme: postgres
Username: user
Password: pass
Host: host.com
Port: 5432
Path: /path
Query: ?k=v
Fragment: #f

This example provides a basic approach to URL parsing in Ada. For more robust URL handling in real-world applications, you might want to consider using or creating a more comprehensive URL parsing library.