CGI Function Example
E-9
Web Programming With the HTTP Server
5) Send appropriate headers.
6) Send the response data. This could be a file or data generated by the CGI
program.
In addition to the commonly used strings defined in section E.4.1, in the exam-
ple function we define some additional strings that are used more than once.
There is also a MACRO to help disguise calls to httpSendClientStr(), and make
the source code a little more readable. These are shown below:
// We use the strings more than once in cgiSample()
static const char *tablefmt = ”<tr><td>%s</td><td>%s</td></tr>\r\n”;
static const char *divider = ”<hr WIDTH=\”100%\”><br>\r\n”
// Page Creation Macro
#define html(str) httpSendClientStr(htmlSock, (char *)str)
Last, the main body of the CGI function. Note that this example is also included
in the example application code in a slightly different form:
static int cgiSample(int htmlSock, int ContentLength )
{
char *name = 0, *spam = 0, *pizza = 0, *color = 0;
char *buffer, *key, *value;
int len;
int parseIndex;
char htmlbuf[MAX_RESPONSE_SIZE];
// 1. Read in the request data
// First, allocate a buffer for the request
buffer = (char*) mmBulkAlloc( Content 1 );
if ( !buffer )
goto ERROR;
// Now read the data from the client
len = recv( htmlSock, buffer, ContentLength, MSG_WAITALL );
if ( len < 1 )
goto ERROR;
// 2. Parse request using cgiParseVars(), or a similar function
// Setup to parse the post data
parseIndex = 0;
buffer[ContentLength] = ’\0’;
// Process request variables until there are none left
do
{
key = cgiParseVars( buffer, &parseIndex );
value = cgiParseVars( buffer, &parseIndex );
if( !strcmp(”name”, key) )
name = value;
else if( !strcmp(”pizza”, key) )
pizza = value;
else if( !strcmp(”spam”, key) )
spam = value;
else if( !strcmp(”color”, key) )
color = value;
} while ( parseIndex != –1 );