Http Server in Pascal
Here’s the translation of the HTTP Server example from Go to Pascal, formatted in Markdown suitable for Hugo:
Our HTTP server example demonstrates how to create a basic HTTP server using Pascal. We’ll use the Synapse library, which provides HTTP server functionality similar to the net/http package.
program HTTPServer;
{$mode objfpc}{$H+}
uses
SysUtils, Classes, httpdefs, fphttpserver;
type
TMyHTTPServer = class(TFPHTTPServer)
public
procedure HandleRequest(var ARequest: TFPHTTPConnectionRequest;
var AResponse: TFPHTTPConnectionResponse); override;
end;
procedure TMyHTTPServer.HandleRequest(var ARequest: TFPHTTPConnectionRequest;
var AResponse: TFPHTTPConnectionResponse);
begin
if ARequest.URI = '/hello' then
begin
AResponse.Content := 'hello' + LineEnding;
end
else if ARequest.URI = '/headers' then
begin
AResponse.Content := '';
for var i := 0 to ARequest.HeaderCount - 1 do
begin
AResponse.Content := AResponse.Content +
Format('%s: %s%s', [ARequest.Headers[i], ARequest.GetFieldValue(ARequest.Headers[i]), LineEnding]);
end;
end
else
begin
AResponse.Code := 404;
AResponse.Content := 'Not Found';
end;
end;
var
Server: TMyHTTPServer;
begin
Server := TMyHTTPServer.Create(nil);
try
Server.Port := 8090;
WriteLn('Server starting on port 8090...');
Server.Active := True;
ReadLn;
finally
Server.Free;
end;
end.In this Pascal example, we create a basic HTTP server using the Synapse library. Here’s a breakdown of the code:
We define a
TMyHTTPServerclass that inherits fromTFPHTTPServer. This class overrides theHandleRequestmethod to process incoming HTTP requests.The
HandleRequestmethod checks the request URI and responds accordingly:- For
/hello, it sends a simple “hello” message. - For
/headers, it echoes back all the request headers. - For any other URI, it returns a 404 Not Found response.
- For
In the main program, we create an instance of
TMyHTTPServer, set the port to 8090, and activate the server.The server runs until the user presses Enter, at which point it shuts down.
To run the server:
- Save the code to a file named
http_server.pas. - Compile the code using the Free Pascal Compiler:
$ fpc http_server.pas- Run the compiled executable:
$ ./http_server
Server starting on port 8090...You can then access the server using curl or a web browser:
$ curl localhost:8090/hello
hello
$ curl localhost:8090/headers
User-Agent: curl/7.68.0
Accept: */*This Pascal implementation provides similar functionality to the original example, demonstrating how to create a basic HTTP server and handle different routes.