Using OCaml to write web scripts
OCaml is a language in which you can do anyything. That's why I decided to use it to write CGI scripts. While it is really easy to use compiled code as a CGI, it is far less simple to use scripts.
Executable ML
Let's start with a very simple script :
Basically, a ml file is not an executable, this can be is achieved in two phases, first a chmod + x on the file, and then we add the following lines in the header file:
The shabang indicates that the interpreter to be used is /bin/sh (nothing new here).
The following three lines are an elegant trick: on the second line, # tells bash that the line is a comment, so it jumps to the new line and calls the toplevel, passing as arguments the name of the script and the rest of the command line.
On the OCaml side, everything which is between (* *) is considered as a comment : OCaml understands the second line as #warnings "A" which is used to display all warnings (alternatively, one can use #wargins "a" to hide all warnings)
Now one can test it by calling ./test.ml
A page saying "Hello OCaml"
The first thing to do is to tell Apache how .ml file should be dealt with, which is achieved by adding the following line to the .htaccess :
Those know Python or Perl won't be suprised, we have to modify slightly our script in order to send the correct headers :
#(*
exec ocaml "$0" "$@"
*) warnings "A";;
print_string "Content-type: text/html\n\n";
print_endline "Hello OCaml !";;
Just check it in your browser