Monday, November 12, 2012

Using Dart Sessions to Pass Information

I ran into a bit of a problem with my Dart-based web server yesterday. It is not a huge problem, but one that I would like to solve. When serving up files from a “public” directory, I am forced to make duplicate file lookups:

In the first addRequestHandler() function, I use publicPath() to decide if this handler should handle the incoming request (if the file exists in the public directory). In the second function, I use the same publicPath() function to locate and read the file from the filesystem when responding to the request.

As I said, this is not a huge deal, but that publicPath() function ultimately calls a blocking existsSync() function:

I do not really mind one blocking lookup, but two? I could build some sort of global cache or variable to hold that information, but first I would like to some way to communication between matcher and responder in addRequestHandler.

I tried setting that information in the request headers yesterday, but Dart treats request heads as immutable. That seems wrong to me—I ought to be able to modify and manipulate header information on the server. But the Dart server is still relatively young, so I won't complain too much.

The only other thing that I can think to try is setting this information in the session. And that does the trick:

I do note (though I do not need it now) that Dart is creating a session ID for me—in case I needed anything in that session upon later requests.

Ultimately, that works, but is overkill for my server. Since the Dart VM is single threaded, I could just as easily use a function global variable to store the current path. Still, it is good to know that I have one way to transfer information to from route matcher to responder.