Wanting to turn the Ploggs, into more RESTful devices, I needed to add a web server (HTTP) to the C++ code managing the Ploggs.
After comparing and trying a number of lightweight web servers (Apache was not an option for this kind of small app) I picked SHTTPD, mainly because:
- It was one of the few I managed to embed in my C++ code (I’m not a C expert…)
- It offered the possibility of registering call back methods when a particular URL is called, which makes it a quite good candidate for a REST interface.
Here is how I did proceed to integrate it to my Microsoft Visual C++ project:
- Compile the project (the core, not the example), this should create a
shttpd.lib
file. - Copy the shttpd.lib, shttpd.h to your src folder (the one of your Visual Studio project).
- Download shttpd.pem and copy it to your src folder as well.
- Add the
shttpd.h
file to your project. - Add the following lib references to your project:
shttpd.lib ws2_32.lib
. - Add the code to start and setup the server. Snippets can be found in the example folder of the SHTTPD distrib. That in my case:
// TestSHTTPD.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include "shttpd.h"#define ALIAS_URI "/my_c"
#define ALIAS_DIR "c:\"static void show_index(struct shttpd_arg *arg) {
shttpd_printf(arg, "%s",
"HTTP/1.1 200 OKrnContent-Type: text/htmlrnrn"
"Welcome to embedded example of SHTTPD");
arg->flags |= SHTTPD_END_OF_OUTPUT;
}int _tmain(int argc, char* argv[])
{
/*
* Initialize SHTTPD context.
* Attach folder c: to the URL /my_c (for windows), and
* /etc/ to URL /my_etc (for UNIX). These are Apache-like aliases.
* Set WWW root to current directory.
* Start listening on ports 8080 and 8081
*/
int data = 1234567;
struct shttpd_ctx *ctx;
ctx = shttpd_init(argc, argv);
shttpd_set_option(ctx, "ssl_cert", "shttpd.pem");
shttpd_set_option(ctx, "aliases", ALIAS_URI "=" ALIAS_DIR);
shttpd_set_option(ctx, "ports", "8080,8081s");/* Register an index page under two URIs */
shttpd_register_uri(ctx, "/", &show_index, (void *) &data);
shttpd_register_uri(ctx, "/abc.html", &show_index, (void *) &data);/* Serve connections infinitely until someone kills us */
for (;;)
shttpd_poll(ctx, 1000);/* Probably unreached, because we will be killed by a signal */
shttpd_fini(ctx);return 0;
}
You should now be able to use the web server within your application.