Howto write an HTTP server

Table of contents

Server initialization

 int main(int argc, char **argv)
 {
   herror_t status;
   hlog_set_level(HLOG_INFO);

   if (httpd_init(argc, argv))
   {
     fprintf(stderr, "Cannot init httpd\n");
     exit(1);
   }

Service registration

   if ((status = httpd_register("/", root_service)) != H_OK)
   {
     fprintf(stderr, "Cannot register service (%s)\n", herror_message(status));
     herror_release(status);
     httpd_destroy();
     exit(1);
   }

   if ((status = httpd_register_secure("/secure", secure_service, simple_authenticator)) != H_OK)
   {
     fprintf(stderr, "Cannot register secure service (%s)\n", herror_message(status));
     herror_release(status);
     httpd_destroy();
     exit(1);
   }

   if ((status = httpd_register("/headers", headers_service)) != H_OK)
   {
     fprintf(stderr, "Cannot register headers service (%s)\n", herror_message(status));
     herror_release(status);
     httpd_destroy();
     exit(1);
   }

   if ((status = httpd_register_default("/error", default_service)) != H_OK)
   {
     fprintf(stderr, "Cannot register default service (%s)\n", herror_message(status));
     herror_release(status);
     httpd_destroy();
     exit(1);
   }

Running the server

   if ((status = httpd_run()) != H_OK)
   {
     fprintf(stderr, "Cannot run httpd (%s)\n", herror_message(status));
     herror_release(status);
     httpd_destroy();
     exit(1);
   }

Server cleanup

   httpd_destroy();

   exit(0);
 }

Sample service function

 static void headers_service(httpd_conn_t *conn, struct hrequest_t *req)
 {
   hpair_t *walker;

   httpd_send_header(conn, 200, HTTP_STATUS_200_REASON_PHRASE);
   http_output_stream_write_string(conn->out,
     "<html>"
       "<head>"
         "<title>Request headers</title>"
       "</head>"
       "<body>"
         "<h1>Request headers</h1>"
         "<ul>");

   for (walker=req->header; walker; walker=walker->next)
   {
     http_output_stream_write_string(conn->out, "<li>");
     http_output_stream_write_string(conn->out, walker->key);
     http_output_stream_write_string(conn->out, " = ");
     http_output_stream_write_string(conn->out, walker->value);
     http_output_stream_write_string(conn->out, "</li>");
   }

   http_output_stream_write_string(conn->out,
         "</ul>"
       "</body>"
     "</html>");

   return;
 }

Generated on Thu Jan 25 23:36:04 2007 for csoap by  doxygen 1.4.6