Home

Installation

Code sample

Reference

Code samples


A first example


#include 

int main( int argc, char** argv)
{
	http_server_t *server;

	server = http_server_new(NULL, "8181");
	server->document_root = "/home/bfleisch/public_html"; // change this

	server->run(server);

	/* NOT REACHED */
	server->delete(server);

	return 0;
}

Compile this program, and run it. Point a web browser a http://localhost:8181/. The result should be the directory listing of the directory /home/bfleisch/public_html.

the http_server_t structure contains all the information regarding the web server. It must be created with the function http_server_new. This functions takes two arguments : a node name and a port value. node_name is the IP address ( or host name ) on which the socket will be bound. If node_name is NULL, the listenning socket will be bound to all the local interfaces ( INADDR_ANY or IN6ADDR_ANY_INIT).
port_value specifies the TCP port for the server. It must be either a number or a service name ( such as httpd ).

Once the structure has been created, you could specify the home directory for your server with document_root, and start the server with server->run(server). Once the server has been started, an infinite loop handles the incoming requests and dispatch them according to the server configuration.

Directory indexes

When a directory URL is requested, if one of the file of the directory indexes list is found in the directory, a redirect page is send to the browser. This directory indexes list should typically contains index.html and/or index.html. This list must be created with list_new function.


	list_t*	indexes;
	
	...
	
	indexes = list_new();
	indexes->add(indexes, "index.html");
	indexes->add(indexes, "index.htm");
	
	server->directory_index = indexes;
	
	...
	
	server->run(server);

Callback functions

A callback function is called whenever the associated URI is found in the request.
An association ( URI, callback function ) is added with the add_url() function in the http_server_t structure :

...
	server->add_url(server, uri, callback_function);
...

The uri parameter is a POSIX regex expression. If a request match this expression, callback_function will be called. The callback_function must follow this prototype :

void cb_func(http_req_t *req, http_resp_t* resp, http_server_t* server).

The http_req_t structure contains information on the current request. We will see later how to get information such as cookies, headers, etc. from this structure.