A Routing CocoaHTTPServer

January 21, 2011

For a recent project I needed to embed an HTTP server in a Cocoa application. After trying a few options I settled on Robbie Hanson’s CocoaHTTPServer. It has worked out well and you only need to read through his blog to see that it’s something he cares about keeping up-to-date.

There were a couple things I wanted to change though. Like the other solutions I tried request handling is performed through connection and response subclasses. This makes sense if the web interface is a bolted-on component, but in my case it was at the core of the app so I was looking for a more integrated API. I also didn’t want to create new response subclasses just to set custom headers and status codes. While I was at it a routing capability similar to Sinatra or Express would save me from performing lots of URL string manipulation.

The result of my tweaking is RoutingHTTPServer, an API on top of CocoaHTTPServer that performs Sinatra-style routing. Here’s how it works:

http = [[RoutingHTTPServer alloc] init];
[http setPort:8000];
[http setDefaultHeader:@"Server" value:@"YourAwesomeApp/1.0"];

[http handleMethod:@"GET" withPath:@"/hello" block:^(RouteRequest *request, RouteResponse *response) {
    [response setHeader:@"Content-Type" value:@"text/plain"];
    [response respondWithString:@"Hello!"];
}];

Convenience methods are available for GET/POST/PUT/DELETE:

[http get:@"/hello/:name" withBlock:^(RouteRequest *request, RouteResponse *response) {
    [response setHeader:@"Content-Type" value:@"text/plain"];
    [response respondWithString:[NSString stringWithFormat:@"Hello %@!", [request param:@"name"]]];
}];

Note that in this example the path is /hello/:name, this will match /hello/world, /hello/you, and so forth. The named parameters in the path are added to the params dictionary in the request object. Query parameters are also included in this dictionary.

Paths can use wildcards:

[http get:@"/files/*.*" withBlock:^(RouteRequest *request, RouteResponse *response) {
    // The "wildcards" parameter is an NSArray of wildcard matches
}];

Or your own regular expressions by wrapping the string in braces:

[http get:@"{^/page/(\\d+)}" withBlock:^(RouteRequest *request, RouteResponse *response) {
    // The "captures" parameter is an NSArray of capture groups
}];

Routes can also be handled with selectors:

- (void)setupRoutes {
    [http handleMethod:@"GET"
              withPath:@"/hello"
                target:self
              selector:@selector(handleHelloRequest:withResponse:)];
}

- (void)handleHelloRequest:(RouteRequest *)request withResponse:(RouteResponse *)response {
    [response respondWithString:@"Hello!"];
}

RouteResponses can respond with an NSString or NSData object, a path to a file, or an existing HTTPResponse class. Responses can also be empty as long as a status code or custom header is set. For example, to perform a redirect:

[http get:@"/old" withBlock:^(RouteRequest *request, RouteResponse *response) {
    [response setStatusCode:302]; // or 301
    [response setHeader:@"Location" value:[self.baseURL stringByAppendingString:@"/new"]];
}];

The server object was also given a couple of enhancements:

CocoaHTTPServer and RegexKitLite are doing almost all of work here, but this addition has sped up my Cocoa HTTP development considerably and I hope it will prove useful for some of you too. You can grab it on GitHub.