program fpwebserver;
{$mode objfpc}{$H+}
uses
{$IFDEF UNIX}
cmem,
cthreads,
BaseUnix,
{$ENDIF}
SysUtils,
fphttpapp,
HTTPDefs,
httproute;
const
cPort = 9191;
procedure DefaultRoute(ARequest: TRequest; AResponse: TResponse);
begin
AResponse.Content:=
'<html>' +
'<head>' +
'<title>FP Web Server</title>' +
'</head>' +
'<body>' +
'<ul>' +
'<li><a href="/">Default</a></li>' +
'<li><a href="/about">About</a></li>' +
'</ul>' +
'<h1>FP Web Server</h1>' +
'<p>Default Route</>' +
'</body>' +
'</html>'
;
end;
procedure AboutRoute(ARequest: TRequest; AResponse: TResponse);
begin
AResponse.Content:=
'<html>' +
'<head>' +
'<title>FP Web Server: About</title>' +
'</head>' +
'<body>' +
'<ul>' +
'<li><a href="/">Default</a></li>' +
'<li><a href="/about">About</a></li>' +
'</ul>' +
'<h1>FP Web Server: About</h1>' +
'<p>About Route</>' +
'</body>' +
'</html>'
;
end;
procedure RegisterRoutes;
begin
// Responds to any method
HTTPRouter.RegisterRoute('/', rmAll, @DefaultRoute, True);
// Responds only to the GET method
HTTPRouter.RegisterRoute('/about', rmGet, @AboutRoute);
end;
{$IFDEF UNIX}
procedure CleanUp(ASignal: LongInt); cdecl;
begin
WriteLn;
WriteLn('Cleaning');
Application.Terminate;
Halt(0);
end;
{$ENDIF UNIX}
begin
RegisterRoutes;
{$IFDEF UNIX}
if FpSignal(SIGINT, @CleanUp) = signalhandler(SIG_ERR) then begin
WriteLn({$I %FILE%}, {$I %LINE%}, Format('Failed to install signal error: %d', [ fpGetErrno ]));
Halt(1);
end;
if FpSignal(SIGKILL, @CleanUp) = signalhandler(SIG_ERR) then begin
WriteLn({$I %FILE%}, {$I %LINE%}, Format('Failed to install signal error: %d', [ fpGetErrno ]));
Halt(1);
end;
{$ENDIF UNIX}
Application.Title:= 'fp-web-httpserver';
Application.Port:= cPort;
Application.Threaded:= True;
Application.Initialize;
WriteLn(Format('Serving on http://localhost:%d', [cPort]));
Application.Run;
end.