Friday, June 05, 2009

Quick Web development with Apache and Haskell (with a slight touch of Perl)

I started learning Haskell a few months ago. It has been a personality changing
experience! Because of the blub paradox - Unfortunately, no one can be told what the Haskell Experience is. You have to feel it for yourself.

Haskell has been the most difficult computer language that I've learnt so far (C,x86 ASM, Perl, Ruby, Java) - From what I understand, my long term exposure to those imperative languages is one of the reasons why I find it difficult.

I am sure, there are many out there who have just begun their Haskell journey. So, here's a quick way in which you could develop Hakell programs that do something interesting - Web development.

Okay, I assume, you know how to setup Perl CGI in your apache web server. It works by default on the Apache installation on my RHEL5 Laptop. The idea is to use a small bridge CGI script in Perl that executes standalone Haskell files and pipes in the CGI parameters into the haskell program and gets back whatever the haskell program writes to its stdout and delivers it back to the web client.

Here's the bridge perl program -


use CGI qw/:standard/;

print header;

$q=new CGI;
%params = $q->Vars;


use FileHandle;
use IPC::Open2;

$pid = open2(*Reader, *Writer, "./$programName" );
for(keys %params){
print Writer "$_ => ".$params{$_}."\n";
close Writer;

@got = <Reader>;
print @got;

So, this bridge simply looks for the program name in the request parameters and then executes it with handles to it's stdin and stdout.

The program to be executed could be a regular Haskell program like this one -

import IO

main = do
getContents <- hGetContents stdin putStrLn ("You entered the following " ++ getContents) =====================