A lightweight HTTP router written in C that makes it easy to route HTTP requests to specific handlers. This project provides a simple interface to create routes, handle client connections, and send HTTP responses. It is designed to be minimal and straightforward, making it ideal for small web services or educational purposes.
- Simple Routing: Easily map HTTP methods and paths to handler functions.
- Customizable Responses: Write custom HTTP headers and bodies.
- Multi-threaded Client Handling: Uses pthreads to handle multiple client requests concurrently.
- POSIX Compliant: Uses POSIX standards for improved portability.
c-http-router/
├── .gitignore
├── LICENSE
├── README.md
├── make.bat
├── Makefile
├── http-router.o
├── test
├── test.c
├── test.o
└── src
├── http-router.c
├── http-router.h
└── http-router.o
- POSIX-compliant operating system (e.g., Linux, macOS)
- A C compiler supporting C99 (or later)
- pthread library (usually provided by default on most systems)
Clone the repository:
git clone https://github.com/BaseMax/c-http-router.git
cd c-http-router
Compile the project:
For example, using gcc:
gcc -pthread -D_POSIX_C_SOURCE=200809L -o c-http-router examples/main.c src/http-router.c
Run the server:
./c-http-router
The server will start listening on port 8080. You can visit http://localhost:8080
in your browser to see the "Home" page and http://localhost:8080/test
for the test page.
To integrate the router into your project:
Include the header file in your source code:
#include "src/http-router.h"
Create a new router instance:
Router *router = http_router_new();
Add routes with their corresponding handler functions:
http_router_add(router, "GET", "/path", your_handler_function);
Start the router on a desired port:
http_router_run(router, 8080);
When finished, stop the router and free resources:
http_router_stop(router);
Below is a simple example demonstrating how to set up a basic HTTP server using the router:
#define _POSIX_C_SOURCE 200809L
#include <unistd.h>
#include "src/http-router.h"
static void route_home_handler(int client_socket) {
const char *body = "<html><body>Home</body></html>";
http_router_write(client_socket, 200, "Content-Type: text/html\r\n", body);
close(client_socket);
}
static void route_test_handler(int client_socket) {
const char *body = "<html><body>Test</body></html>";
http_router_write(client_socket, 200, "Content-Type: text/html\r\nX-Powered-By: C\r\n", body);
close(client_socket);
}
int main(void) {
Router *router = http_router_new();
http_router_add(router, "GET", "/", route_home_handler);
http_router_add(router, "GET", "/test", route_test_handler);
http_router_run(router, 8080);
http_router_stop(router);
return 0;
}
This example creates a router, adds two routes ("/" and "/test"), and starts the HTTP server on port 8080.
This project is licensed under the MIT License.
For questions or suggestions, please open an issue on the GitHub repository.
Enjoy building your web app with c-http-router!