Simple C++ CGI Example

I guess I will share with you some of the things I have been working on. I have been working on a C++ CGI that will accept a post, process, and then return the results. This is completely new to me so the code isn’t mind boggling or anything. However, after checking various places the examples all seem to be broken or have strange implementations. Runs in GCC 4.x.

#include <iostream>
#include <string>
using namespace std;

int main()
{
	char * lpszContentLength = getenv("CONTENT_LENGTH");
	string strOutput;

	if (lpszContentLength != NULL)
	{
		int bufLen = atoi(lpszContentLength) + 1;
		char * lpszBuffer = new char[bufLen];
		memset(lpszBuffer, 0, bufLen);
		fread(lpszBuffer, 1, bufLen, stdin);

		strOutput = "Content-type: text/html\r\n\r\n";
		strOutput += "<html>\r\n";
		strOutput += "<body>\r\n";
		strOutput += "<p>\r\n";
		strOutput += "Hello! You sent " + string(lpszContentLength) + " bytes of data which read: <br>\r\n";
		strOutput += string(lpszBuffer) + "\r\n";
		strOutput += "</p>\r\n";
		strOutput += "</body>\r\n";
		strOutput += "</html>\r\n";

		delete [] lpszBuffer;
	}
	else
	{
		strOutput = "Content-type: text/xml\r\n\r\n";
		strOutput += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n";
		strOutput += "<webService>\r\n\t<service>\r\n\t\t<statusCode>0</statusCode>\r\n";
		strOutput += "\t\t<statusMessage>Malformed request recieved. Unable to process.</statusMessage>\r\n";
		strOutput += "\t</service>\r\n\t<data />\r\n</webService>\r\n";
	}
	
	cout << strOutput << endl;
  
  return 0;
}

I’ve also been doing some bug fixing and consolidation for the various stuff we have going on here. I have been updating a lot of the older functions and converting them to classes while also simplifying a lot of how things work.

I was very discouraged about my venture into C++. A co-worker suggested I study data structure; OS; algorithms; databases; networking, graphics or compilers; and then platforms before tackling a project in something like C++. I admit that the myriad of pointers, memory allocation, etc. is quite daunting but I am very eager to learn new things. I will definitely take on learning all those things.

At the same time, maybe I should just adopt a web service like SOAP. Maybe I am going about this all wrong.

This entry was posted in Uncategorized. Bookmark the permalink.

Comments are closed.