Sunday, June 24, 2012

Added Node.js Connect Style "Middleware" To ALE


Inspired by Connect

I've added middleware functionality to ALE. This was mostly to lay the groundwork for a routed server. The idea borrows heavily from the Node.js module Connect. Basically, this just allows the developer to register a series of methods that will be executed in order as the request is processed. In JavaScript, however, this requires the use of a cumbersome "next()" function object that gets passed to each piece of middleware as a means of calling the next. Since we have events and delegates in C#, that isn't necessary, and it's a little cleaner, IMO.

To implementation looks like so:

EventLoop.Start(() => 
{
   Server.Create()
      .Use(DoSomePrepWork)
      .Use((req, res) => {
         var foo = req.Context.ContextBag.Foo;
         res.Write("Foo: " + foo + "

");
      })
      .Use(DoSomeLogging)
      .Listen("http://*:1337/");
});

Where there would be methods for middleware like so:

public void DoSomePrepwork(IRequest req, IResponse res)
{
   res.Context.ContextBag.Foo = "Wut, wut, wut? Socks and sandles!";
}

public void DoSomeLogging(IRequest req, IResponse res) 
{
   Logger.Log("A request was made to: " + req.Url);
}



What is middleware? How will it be used?


Well, in this case it's a poor use of a term that has sort of stuck when it comes to Node.js. Normally middleware would be considered to be some broker software, like a proxy, or a web api, or something like that. In this case it's just some code that is being executed between some other calls.




Because of what it is, I think it should be obvious how this could be used. It could be used for logging, or reporting, or authentication or additional processing of incoming requests or any sort. I realize at this point the server really only does one thing, and that there's no reason you couldn't just code your pre-processing and post-processing directly into the body of a single processing delegate... But I added this to lay the ground work for a routing implementation that will be coming in the near future.

No comments:

Post a Comment

This form allows some basic HTML. It will only create links if you wrap the URL in an anchor tag (Sorry, it's the Blogger default)