Joo, JavaScript on OCaml
My readers might have noticed that I really like JavaScript and OCaml. Thus, it's natural to write a webserver in OCaml which serves scripts written in JavaScript. Crazy ? Maybe a little, but as the guys from mod_js said: others do worse.
I started by modifying Thumper which I slightly modified (in order to deal with post queries). Then I added OCaml CGI to encode and decode queries, SpiderCaml which includes SpiderMonkey in OCaml and OCaml Mysql to use MySQL. Actually this was more like doing Lego than coding…
What can it do ?
URIs are parsed as : /module/action/arg1/arg2/arg3. This will execute Module.action(arg1, arg2, arg3), where Module is defined in the file modules/module.js. The default module being home and the default action, index.
This being said, their is a Joo object in the global namespace which contains useful stuff:
for (e in Joo.Headers) print(e+" "+Joo.Headers[e]+"<br/>");
// GET
for (e in Joo.Get) print(e+" "+Joo.Headers[e]+"<br/>");
// POST
for (e in Joo.Post) print(e+" "+Joo.Headers[e]+"<br/>");
// a mysql wrapper
Joo.mysql.connect({
host:"localhost",
user:"user",
name:"database"
});
Joo.mysql.query('select * from foo');
while(r = Joo.mysql.fetch()) print(r.id + "<br/>");
// an include function
Joo.include('foo/bar.js');
Note : the print function just adds text to the output buffer, their is no control on the flushing, sorry. Everything is sent at the end.
Moreover, I have added the MIME types only for html and jpeg files, you may want to add other MIME types in main.ml
One Response to "Joo, JavaScript on OCaml"
Great to see somebody actually took a look at the thumper code - hope it wasn't too traumatic.
Cool stuff - I'm sure there's more mature Ocaml HTTP servers out there than my thumper hack job, maybe you should try and make something more of this JS+Ocaml+HTTP thing?
Leave a Reply