Http Client in Ada

Here’s the translation of the HTTP Client example from Go to Ada, formatted in Markdown suitable for Hugo:

Our example demonstrates how to make HTTP requests using Ada. We’ll use the AWS.Client package, which provides excellent support for HTTP clients.

with Ada.Text_IO;
with AWS.Client;
with AWS.Response;
with AWS.Messages;

procedure HTTP_Client is
   Response : AWS.Response.Data;
   URL      : constant String := "https://example.com";
begin
   -- Issue an HTTP GET request to a server
   Response := AWS.Client.Get (URL);

   -- Print the HTTP response status
   Ada.Text_IO.Put_Line ("Response status: " & 
      AWS.Messages.Status_Code'Image (AWS.Response.Status_Code (Response)));

   -- Print the first 5 lines of the response body
   declare
      Body : constant String := AWS.Response.Message_Body (Response);
      Start, End_Index : Natural := Body'First;
      Line_Count : Natural := 0;
   begin
      while End_Index <= Body'Last and Line_Count < 5 loop
         End_Index := Ada.Strings.Fixed.Index (Body (Start .. Body'Last), Ada.Characters.Latin_1.LF);
         if End_Index = 0 then
            End_Index := Body'Last;
         else
            End_Index := End_Index - 1;
         end if;
         
         Ada.Text_IO.Put_Line (Body (Start .. End_Index));
         
         Start := End_Index + 2;
         Line_Count := Line_Count + 1;
      end loop;
   end;
exception
   when E : others =>
      Ada.Text_IO.Put_Line ("An error occurred: " & Ada.Exceptions.Exception_Message (E));
end HTTP_Client;

To run the program, compile it with your Ada compiler (e.g., GNAT):

$ gnatmake http_client.adb
$ ./http_client
Response status: 200 OK
<!DOCTYPE html>
<html>
  <head>
    <title>Example Domain</title>
    <meta charset="utf-8">

This Ada program does the following:

  1. It uses the AWS.Client.Get function to send an HTTP GET request to the specified URL.

  2. The response status is printed using AWS.Messages.Status_Code'Image to convert the status code to a string.

  3. To print the first 5 lines of the response body, we use a loop that searches for newline characters in the response body string. This is a bit more involved in Ada compared to the Go example, as Ada doesn’t have a built-in line scanner like Go’s bufio.Scanner.

  4. Error handling is done using Ada’s exception handling mechanism. Any unexpected errors are caught and their messages are printed.

Note that this example uses the Ada Web Server (AWS) library, which needs to be installed and linked with your program. The AWS library provides functionality similar to Go’s net/http package for HTTP operations in Ada.