libhttpdLinux

libhttpd is designed to be a very small, lightweight and simple library that allows developers to add a web server to their project.

I started work on this library to aid the development of my home automation system. Rather than write a number of CGI scripts that would in turn communicate with my various sub-systems (using sockets or IPC), I decided that it may be easier to build a single large service. This also lowers the dependencies required to deploy my system, no Apache or other web server with support for CGI - just a single binary.

Links

Overview

To use libhttpd, you simply need to call a 'setup' function, and hand it a callback function. When a browser (or anything talking HTTP) connects, libhttpd starts a new thread, parses the request, and calls your callback. In your callback, you can easily determine the URI requested, the method, and access any HTTP headers that were sent. You then build the response, and return from the callback. After your callback has completed, libhttpd will build the response (including any headers you added), and the thread terminates.

Example

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <httpd.h>
  5.  
  6. int client_callback(int rxid, struct xfer_info *info, char *content, int contentLength) {
  7.  
  8.   printf("New client! %d\n", rxid);
  9.  
  10.   httpd_respond(info, "Testing %d %d %d...\r\n", 1, 2, 3);
  11.   httpd_respond(info, "URI requested: '%s'\r\n", httpd_getURI(info));
  12.   httpd_respond(info, "Host: '%s'\r\n", httpd_getHeader(info, "host"));
  13.  
  14.   return 0;
  15. }
  16.  
  17. int main(int argc, char *argv[]) {
  18.   struct httpd_info *httpd;
  19.   hte ret;
  20.  
  21.   if ((ret = httpd_startServer(&httpd, 8080, client_callback)) != HTE_NONE) {
  22.     printf("httpd_startServer() returned %d\n", ret);
  23.     return 1;
  24.   }
  25.  
  26.   printf("Running for 60 secs!\n");
  27.  
  28.   sleep(60);
  29.  
  30.   return 0;
  31. }