Web API alternative - self hosting HTTP services in native C++ code

Strath

December 4th, 2012

Web API alternative – self hosting HTTP services in native C++ code

Because sometimes the inherent efficiency of C++ is just too important

On this blog, I’ve been focusing pretty much exclusively on ASP.NET Web API, but today let’s step outside .NET, and explore how you could host RESTful HTTP services directly from the native unmanaged C++ code – and I hope, this is going to be a very interesting journey, especially as C++ is so much more efficient than any managed language.

If you haven’t done C++ before, or haven’t done any in years, don’t dread, modern C++ is quite different than what you might be used to of have heard of. Microsoft DevLabs and Niklas Gustafsson provide a terrific experimental library called Casablanca, which is a C++ SDK aimed at creating modern HTTP services in native code.

More after the jump.

Getting started with Casablanca

You can grab the Casablanca SDK for Visual Studio 2012 from here and you can read up about the project here.

The main strengths of Casablanca is that it provides C++ developers a number of wrappers around functionality that otherwise are very difficult to achieve with pure C-level coding:
– self hosting a server using HTTP listeners
– implementations of very unusual in C++ world, but common for .NET developers concepts like JSON, HTTP status codes, URI and so on
– very powerful asynchronous model (and, yes, asynchrony in C++ is much more difficult than anything you might be used to in managed languages)
– integration into Azure
– very good actor programming model, derived from Erlang

Once you installed the SDK, we are ready to go.

Creating a self-hosted server in native C++ application

If you used ASP.NET Web API self hosting, or anything that implemented HTTP Listeners in C#, this should feel very familiar. We are going to create a C++ application and self host a server in there, and then interact with it from the browser.

Let’s start with creating a new app, C++, Win32 Console Application, the default wizard settings are fine. Now we need to add references to Casablanca. There a few ways to achieve this, but the quickest is to modify the project’s properties. Go to the properties and:
– under VC++ Directories, add the entry for Executable Directories:
$([MSBuild]::GetRegistryValue(HKEY_CURRENT_USER\Software\Microsoft\Casablanca\110\SDK, InstallDir))\bin\x86\Debug;$(ExecutablePath)
– under C/C++, add the entry for Additional Include Directories:
$([MSBuild]::GetRegistryValue(HKEY_CURRENT_USER\Software\Microsoft\Casablanca\110\SDK, InstallDir))\include
– under Linker, add the entry for Additional Library Directories:
$([MSBuild]::GetRegistryValue(HKEY_CURRENT_USER\Software\Microsoft\Casablanca\110\SDK, InstallDir))\lib\x86\Debug
– under Linker > Input add the following entry for Additional Dependencies:
casablanca110.lib;kernel32.lib;user32.lib;gdi32.lib;winspool.lib; comdlg32.lib;advapi32.lib;shell32.lib;ole32.lib;oleaut32.lib; uuid.lib;odbc32.lib;odbccp32.lib;%(AdditionalDependencies)

And off we can go!

We will be self hosting inside our app using http_listener.h, so sure enough, we need to import this header file. You might do that in the stdafx.h or however you like to organize you dependencies.

To self host we need:
– a localhost URI + port for our HTTP server to listen at,
astreambuf.h, iostream from Standard Library and the aforementioned http_listener.h
– a lambda that will be used to provide a response to an incoming HTTP request, more on that later

Again, if you used Web API self host this looks awfully familiar. We start off by importing two Casablanca namespaces, and declare a localhost address. Then we pass it in the constructor of the http_listener. Additionally, we pass in a lambda – for providing a GET handler for incoming requests.

The constructor actually has some overloads and can take in 4 lambdas – for GET, PUT, POST and DELETE – but in this simple example we only handle GET.

At the end of this code bit, we simply tell the server to listen to any incoming requests until someone hits enter to close the application.

Before we run this app, you need to copy two files to the build folder (since the installation of the SDK will not modify your PATH settings):
– casablanca110.dll
– casablanca110.pdb

For debug builds you can copy these files from C:\Program Files (x86)\Microsoft Code Name Casablanca SDK for VS 2012\SDK\bin\x86\Debug to your Debug folder.

If we now run the application and point our browser to http://localhost:4999/ and voila:

Self hosting from C++ working like a charm. Of course this example was very simple, so let’s add a little twist – and return and accept JSON.

RESTful service with C++

Let’s add a simple class Person, which we will send down over the wire to the HTTP client as JSON and which we will accept in the POST method as client’s input (in JSON as well).

Header:

Implementation:

Because we are going to convert this class to JSON, we need to add additional methods for handling to-JSON and from-JSON conversion. The to-JSON one can be invoked off an existing person pointer but the from-JSON will be static.

So in the Person.cpp we add:

And in the header we add the definition and the static method:

We are using here the wonderful JSON functionalities provided by Casablanca – in this case, http::json::value. Notice that the JSON implementation requires csablanca::string_t, Casablanca’s version of string so we use utility functions to convert back and forth from std::string.

Now we can enhance our server a bit, by passing in lambdas to handle not just GET but other HTTP verbs as well:

The order of lambdas is actually: GET, PUT, POST and DELETE. We don’t do much here except serving an object on GET, accepting input on POST/PUT and respoding with relevant HTTP status code (such as “no content”). I am also logging the activities in the command line output to keep track of what’s going on.

If we run this application now, we can send all kinds of RESTful requests:

GET:

POST:

PUT:

DELETE:

How cool is that?

Source code and summary

Of course the examples here are very simple, but hopefully you get the idea that actually self hosting in native C++ is a damn piece of cake with Casablanca. There are many other HTTP concepts that we didn’t even touch on here, so if there is a need to go deeper, we can have more posts in the future :)

You can apply pretty much all of your HTTP knowledge because Casablanca provides very nice (for C++ standards) model to work with all of the cornerstones of HTTP – response codes, headers, content types (nice JSON support) and such.

Of course it’s still C++, so you better know what you are doing, but for high performance tools, this is a very, very viable option for providing a modern HTTP service and an great alternative to its managed language counterparts. And all I can say in the end, is “thanks, Niklas”.

– Source code for the example is on Github

Be Sociable, Share!