Thursday, October 21, 2010


Web 2.0 programming with Object Pascal (Part 3)

Debugging CGI applications

If you build web applications, surely often you'll face the need of a way to debug them. Remember that CGI or FastCGI applications run inside the Web Server, and you can't debug them by placing breakpoints in your Lazarus code.

The easiest way I found to debug web applications is by using the "dbugintf" unit, provided by FreePascal. This unit, according to the FCL documentation can be used " add debug messages to your application. The messages are not sent to standard output, but are sent to a debug server process which collects messages from various clients and displays them somehow on screen", both, FreePascal and Lazarus include example debug servers to cath messages generated in apps.

How to use dbugintf unit

This is easy, just add dbugintf to the "uses" of the units you want to debug, then use SendDebug to send messages to the debug server.


Using Lazarus, go to Project -> New Project -> CGI Application to create a new CGI application, then go to the FPWebModule1 automatically created by Lazarus, and then to the Object Inspector, select Events and double click on the "OnRequest" event handler to create the skeleton for this handler, then adapt it to look like this:

unit Unit1;

{$mode objfpc}{$H+}


Classes, SysUtils, FileUtil, HTTPDefs, websession, fpHTTP, fpWeb;


{ TFPWebModule1 }

TFPWebModule1 = class(TFPWebModule)
procedure DataModuleRequest(Sender: TObject; ARequest: TRequest;
AResponse: TResponse; var Handled: Boolean);
{ private declarations }
{ public declarations }

FPWebModule1: TFPWebModule1;


{$R *.lfm}

{ TFPWebModule1 }

procedure TFPWebModule1.DataModuleRequest(Sender: TObject; ARequest: TRequest;
AResponse: TResponse; var Handled: Boolean);
AResponse.Content := 'Hello!';
SendDebug('--->Debug this!<---');
Handled := True;

RegisterHTTPModule('TFPWebModule1', TFPWebModule1);

Then compile the program, and copy it to your web server's cgi-bin directory and test using your web browser. If everything is ok, you'll note just a web page containing the text "Hello!".

Introducing debugserver

As I explained at the beginning of this article, to catch the debugging messages you need to use a debug server. In the sources of Lazarus you can find a tool called "debugserver" placed in lazarus-sources/tools/debugserver, open it with Lazarus and compile, then Run.

In Unix/Linux, After running the debugserver, you'll note it creates the file /tmp/debugserver. In my case, that file is created with 600 permissions, that is, read only. To let the cgi program write to that file, just do this:

sudo chmod 666 /tmp/debugserver

Now you can try again your program using the web browser, and look at the debugserver screen, it should add the message "--->Debug this!<---" to the messages list.

That's all, hopefully you find this interesting.

This page is powered by Blogger. Isn't yours?