D2 & Web-Framework

Adam Ruppe destructionator at gmail.com
Thu Jul 14 06:46:57 PDT 2011


> http://arsdnet.net/dcode/

In there, you'll find most my files for the websites I create in D.

The basic one is cgi.d. It gives easy access to things like get and
post variables, uploaded files, and writing out responses. I think
it works standing alone, but it might require the sha.d in there too
now (I've been a little sloppy on that stuff recently.)

Example:

===
import arsd.cgi;

void mySite(Cgi cgi) {
  if("name" in cgi.get)
    cgi.write("hello, world, "~cgi.get["name"]~"!");
  else
    cgi.write("Hello! Add ?name=yourname to the url for a message.");
}

mixin GenericMain!mySite;
====


the genericmain creates a main() function that creates the cgi object
for you and calls the given function.

cgi.get and cgi.post are plain immutable string[string] for getting
parameters.

There's a lot of stuff in there, but just this can do a fair amount.
Pretty straightforward stuff.



Also in that folder are a bunch of helpers. database.d and mysql/postgres/sqlite
for databases.

dom.d provides a javascript style DOM. I use this for templating -
create a Document object from an existing html file. Then, insert
your data or otherwise manipulate it. Then, at the end, do a
cgi.write(document.toString()); to finish it off.

Of course, you don't have to do it that way.


Finally, web.d builds on top of dom and cgi to provide a higher
level interface; instead of manually parsing the cgi object, it tries
to do it automatically, to call your functions with reflection.

Example:
=====
import arsd.web;
class MySite : ApiProvider {
   string hello(string name) { return "Hello, " ~ name ~ "!"; }
}
mixin FancyMain!MySite;
=====

(the base class is called ApiProvider right now because I found it
was great for producing functions to be called from javascript - all
automatically - but it was originally made for doing full sites.)


What it does is takes a class and makes it's functions callable via
urls. The arguments are used to build automatic forms, if needed, to
ask the user for parameters and the return value is used to build
a response in various data formats.

The cgi object is a member of the ApiProvider base class, so you can
always use it in a more traditional manner too, ignoring most the
fancy wrapper and just writing void, argumentless functions. However,
then you lose a lot of the good stuff!


Anyway it's default output is a DOM document. You can override methods
from the base class to provide your own document and post processor.



I've been light on writing documentation for any of this, but cgi.d
at least should be pretty straight forward for doing work with.


More information about the Digitalmars-d mailing list