About that compact web server
February 17th, 2008 by pimIt’s funny to notice how, subconsciously, the way things work in Grace turn out to look eerily similar to how they work in Python. I was reminded of that fact again when I read this article, illustrating a 15 line web server implementation in Python. This is how it would look in Grace:
#include <grace/daemon.h>
#include <grace/httpd.h>
class myApp : public daemon
{
public:
myApp (void) : daemon (”myapp”) {}
~myApp (void) {}
int main (void);
};
class helloPage : public serverpage
{
public:
helloPage (httpd &p) : serverpage (p, “/foo”) {}
~helloPage (void) {}
int execute (value &env, value &argv,
string &out, value &outhdr)
{
if (! argv.exists (”target”))
argv["target"] = “world”;
out = “Hello, %[target]s\n” %format (argv);
return 200;
}
};
$application (myApp);
$version (1.0);
int myApp::main (void)
{
httpd srv (8180);
value event;
new helloPage (srv);
daemonize ();
srv.start ();
while (event.type() != “shutdown”)
event = waitevent ();
httpd.shutdown ();
return 0;
}
Admittedly this is a bit more than 15 lines (even if we don’t count lines with curly brackets). We do get a little bit more oomph for those lines, though:
- The application checks a pid-file in /var/run or ${HOME}/var/run.
- The application is forked to the background
- The application responds sanely to SIGTERM
Having an easily extendible web server built into your framework turns out to be pretty convenient: It’s a very quick way to deploy a remotely accessible service.
Tags: c++, grace, programming, python











