Csilk 0.2.1
A lightweight, high-performance C HTTP web framework
Loading...
Searching...
No Matches
csilk

A lightweight, high-performance HTTP web framework written in C, inspired by Gin (Golang) and built on top of libuv, llhttp, and cJSON.

Features

  • ๐Ÿš€ High performance using libuv for asynchronous I/O
  • ๐Ÿš€ Zero-copy Static File Serving via sendfile integration
  • ๐Ÿ“ฌ Internal Event Bus - Asynchronous, thread-safe Message Queue with middleware and subscriber support
  • ๐Ÿ“ˆ Native Prometheus Metrics - Built-in observability for QPS, latency, and status codes
  • ๐Ÿ–ฅ๏ธ Unified Admin Dashboard - Web-based real-time monitoring of HTTP, AI Workflows, and MQ
  • ๐Ÿ›ก๏ธ Native HTTPS/TLS support via OpenSSL integration
  • ๐Ÿ”‘ JWT (JSON Web Token) authentication middleware (HS256)
  • ๐Ÿ”Œ Extensible Hook system for lifecycle events (Server, Connection, Request)
  • ๐Ÿ”ง Pluggable Crypto Driver for custom hashing and UUID algorithms
  • ๐Ÿ” Pluggable Cipher Driver for AES-256-GCM, RSA-OAEP, and RSA-PSS
  • ๐Ÿ—„๏ธ Pluggable Database Drivers - SQLite, MySQL, PostgreSQL, MongoDB, Redis
  • ๐Ÿ”ง Middleware support (logger, recovery, auth, CORS, CSRF, rate limiting, static files)
  • ๐ŸŒ RESTful API routing with parameter handling and route groups
  • ๐Ÿ“ฆ JSON support via cJSON (parse, serialize, error responses, reflection binding)
  • ๐Ÿช Cookie parsing and setting (with Max-Age, Secure, HttpOnly, etc.)
  • ๐Ÿ”Œ WebSocket support (RFC 6455 handshake, frame send/receive)
  • ๐Ÿ“ก Server-Sent Events (SSE) with csilk_sse_init/send/close
  • ๐Ÿ“ฆ Gzip response compression middleware (with intelligent skipping for media)
  • ๐Ÿ“ค Multipart/form-data file upload parsing
  • ๐Ÿ” URL parsing and query string handling
  • โšก Keep-alive connection support
  • ๐Ÿ›ก๏ธ Graceful error handling with crash recovery (setjmp/longjmp)
  • ๐Ÿ“‹ YAML configuration (server, logger, CORS, rate limit, static files, middleware)
  • ๐Ÿ—๏ธ Arena allocator for request-scoped memory management
  • ๐Ÿค– Unified AI Interface - Provider-agnostic API for Chat, Embeddings, and Tool Calling (OpenAI & Ollama)
  • ๐Ÿ—‚๏ธ Reflection engine for automatic struct <-> JSON conversion (including basic types and arrays)
  • ๐Ÿ” Built-in CSRF protection, CORS, and rate limiting
  • ๐Ÿ“ Complete Doxygen documentation for all public APIs and internals
  • ๐Ÿงต Thread-safe logging with file rotation and ANSI colors
  • ๐Ÿ” Configurable connection timeout and body/header size limits
  • ๐ŸŽฏ Global (server-level) and per-route middleware support
  • ๐ŸŒฒ Radix Tree router with :param and *wildcard matching
  • ๐Ÿ“ Form URL-encoded body parsing (application/x-www-form-urlencoded)
  • ๐Ÿช Session management with thread-safe mutex protection
  • ๐Ÿ”€ HTTP redirect helper (csilk_redirect)
  • ๐Ÿ“„ HTTP Range request support (206 Partial Content) for static files
  • โœ… Request parameter validation middleware (required, int, string, email)
  • ๐Ÿ†” Request ID middleware for end-to-end tracing (X-Request-Id)
  • ๐Ÿฉบ Built-in Health Check handler (/healthz)
  • ๐Ÿ“ฆ Opaque Context API for ABI stability

Dependencies

  • libuv - Asynchronous I/O library
  • llhttp - HTTP parser
  • cJSON - JSON parser
  • libyaml - YAML parser
  • OpenSSL - TLS/SSL and Cryptographic library (Required for HTTPS and JWT)

libuv and cJSON are automatically fetched during build via CMake's FetchContent. llhttp is used from the system if available, otherwise fetched. libyaml and OpenSSL must be installed as system dependencies.

Installation (Debian/Ubuntu)

sudo apt install libyaml-dev libssl-dev

Building

Prerequisites

  • CMake 3.11 or higher
  • C compiler (supporting C11)
  • Git (for fetching dependencies)
  • libyaml development headers (apt install libyaml-dev on Debian/Ubuntu)

Build Steps

# Clone the repository
git clone https://github.com/yourusername/csilk.git
cd csilk
# Create a build directory
mkdir build && cd build
# Configure with CMake
cmake ..
# Build
make
# By default, csilk builds as a static library.
# To build as a shared library, use:
# cmake .. -DBUILD_SHARED_LIBS=ON
#
# Other available options:
# -DUSE_ASAN=ON Enable AddressSanitizer (default OFF)
# -DCSILK_BUILD_SHARED=ON Build shared library (default OFF)
# -DUSE_FUZZER=ON Enable libFuzzer (default OFF)
# Optional: Run tests
make run_tests # Runs all tests via ctest
# or: ctest --test-dir . --output-on-failure
# Optional: Run individual test
./tests/test_logger
# ... other test executables
# Optional: Build documentation
make docs # Requires Doxygen
# Optional: Format code
make format # Requires clang-format

Documentation

API documentation is written using Doxygen comments throughout the codebase. All public API functions, types, enums, and macros in the headers (include/csilk/csilk.h, include/csilk/app/app.h, include/csilk/core/internal.h, include/csilk/reflection/reflect.h) are fully documented with @brief, @param, and @return tags. Implementation files in src/ subdirectories also carry complete Doxygen documentation with consistent @copyright and license annotations.

Online documentation is available at: https://quintin-lee.github.io/csilk/

To generate HTML documentation locally:

cd build && cmake .. && make docs # Or: doxygen Doxyfile

Open docs/html/index.html in your browser to browse the API reference.

Documentation Coverage

Component Status
include/csilk/ (public API hierarchy) Fully documented
src/core/ (kernel implementation) Fully documented
src/app/ (app layer) Fully documented
src/ai/, src/data/, src/security/ Fully documented
src/middleware/ (middleware) Fully documented
examples/ (example code) Fully documented

Usage

Simple Server Example

#include "csilk/csilk.h"
void hello_handler(csilk_ctx_t* c) {
csilk_string(c, 200, "Hello World!");
}
void ping_handler(csilk_ctx_t* c) {
csilk_string(c, 200, "pong");
}
int main() {
// Create router
// Define routes
csilk_handler_t hello_handlers[] = {hello_handler};
csilk_router_add(router, "GET", "/", hello_handlers, 1);
csilk_handler_t ping_handlers[] = {ping_handler};
csilk_router_add(router, "GET", "/ping", ping_handlers, 1);
// Create and run server
csilk_server_t* server = csilk_server_new(router);
csilk_server_run(server, 8080);
// Cleanup (never reached in this example)
return 0;
}
void ping_handler(csilk_ctx_t *c)
Simple ping handler โ€” returns "pong".
Definition advanced_server.c:96
High-performance C web framework โ€” main public API header.
The main HTTP router.
Definition csilk.h:1419
void csilk_string(csilk_ctx_t *c, int status, const char *msg)
Set a plain-text response body and status code.
Definition context.c:214
void csilk_server_free(csilk_server_t *server)
Destroy the server and release all resources.
Definition server.c:1647
void(* csilk_handler_t)(csilk_ctx_t *c)
Function pointer for route handlers and middleware.
Definition csilk.h:120
csilk_server_t * csilk_server_new(csilk_router_t *router)
Create a new server instance.
Definition server.c:1469
int csilk_server_run(csilk_server_t *server, int port)
Start the server and enter the libuv event loop.
Definition server.c:2137
csilk_router_t * csilk_router_new(void)
Create a new empty router.
Definition router.c:204
void csilk_router_add(csilk_router_t *r, const char *method, const char *path, csilk_handler_t *handlers, size_t handler_count)
Register a route with one or more handlers.
Definition router.c:489
void csilk_router_free(csilk_router_t *r)
Destroy the router and release all its resources.
Definition router.c:221
int main(void)
Definition example_app.c:388
void hello_handler(csilk_ctx_t *c)
Handler for GET / โ€” returns welcome message.
Definition example_server.c:120

Route Groups

// Define handlers
void data_handler(csilk_ctx_t* c) {
csilk_string(c, 200, "data response");
}
int main() {
// Create a route group with "/api" prefix
csilk_group_t* api = csilk_group_new(router, "/api");
// Use convenience macros to add routes
csilk_GET(api, "/data", data_handler);
// -> matches GET /api/data
// ...
}
#define csilk_GET(group, path, handler)
Register a GET route on the group.
Definition csilk.h:1801
csilk_group_t * csilk_group_new(csilk_router_t *router, const char *prefix)
Create a new route group with a URL prefix.
Definition group.c:132

Middleware Usage

void my_middleware(csilk_ctx_t* c) {
// Custom logic before next handler
}
// Built-in middleware handlers:
// csilk_logger_handler - Request logging
// csilk_recovery_handler - Panic recovery (500 on panic)
// csilk_auth_middleware - Token authentication (with validator callback)
// csilk_static - Static file serving (with root directory)
// Middleware is applied to route groups:
csilk_group_t* group = csilk_group_new(router, "/api");
void csilk_next(csilk_ctx_t *c)
Pass control to the next handler in the middleware/handler chain.
Definition context.c:165
void csilk_recovery_handler(csilk_ctx_t *c)
Panic-recovery middleware.
Definition recovery.c:36
void csilk_group_use(csilk_group_t *group, csilk_handler_t handler)
Add middleware to a group.
Definition group.c:195
void csilk_logger_handler(csilk_ctx_t *c)
Logging middleware handler. Logs request method, path, and processing time.
Definition logger.c:79

HTTPS & JWT Example

#include "csilk/csilk.h"
void secure_handler(csilk_ctx_t* c) {
cJSON* payload = (cJSON*)csilk_get(c, "jwt_payload");
const char* user = cJSON_GetObjectItem(payload, "sub")->valuestring;
char msg[64];
snprintf(msg, sizeof(msg), "Hello secure user: %s", user);
csilk_string(c, 200, msg);
}
int main() {
csilk_group_t* api = csilk_group_new(router, "/api");
// Apply JWT middleware to /api group
csilk_GET(api, "/profile", secure_handler);
csilk_server_t* server = csilk_server_new(router);
// Configure HTTPS
csilk_server_config_t config = {0};
config.enable_tls = 1;
config.tls_cert_file = "cert.pem";
config.tls_key_file = "key.pem";
csilk_server_set_config(server, &config);
csilk_server_run(server, 443);
return 0;
}
char * tls_cert_file
Definition csilk.h:984
int enable_tls
Definition csilk.h:982
char * tls_key_file
Definition csilk.h:986
Low-level server configuration options.
Definition csilk.h:953
void csilk_server_set_config(csilk_server_t *server, const csilk_server_config_t *config)
Apply server configuration options.
Definition server.c:1730
void csilk_jwt_middleware(csilk_ctx_t *c, const char *secret)
JWT authentication middleware.
Definition jwt.c:235
void * csilk_get(csilk_ctx_t *c, const char *key)
Retrieve an opaque value from the request context.
Definition context.c:1020
static void user(csilk_ctx_t *c)
Handler for GET /user/:id โ€” returns the user ID from path param.
Definition example_app.c:176

Project Structure

src/
โ”œโ”€โ”€ core/ # Kernel (libuv TCP, Router, Arena, Logger, Config)
โ”œโ”€โ”€ app/ # Application Layer (app, admin dashboard, workflow engine)
โ”œโ”€โ”€ ai/ # AI Unified Interface Engine
โ”œโ”€โ”€ crypto/ # Cipher Driver (AES, RSA, sign/verify)
โ”œโ”€โ”€ data/ # Database Abstraction Layer
โ”œโ”€โ”€ messaging/ # Internal Event Bus (Message Queue)
โ”œโ”€โ”€ security/ # Permission & Security Core
โ”œโ”€โ”€ reflection/ # Reflection Engine implementation
โ”œโ”€โ”€ protocols/ # Protocol Extensions (WebSocket, Swagger)
โ”œโ”€โ”€ drivers/ # Concrete Drivers (OpenAI, Ollama, SQLite, MySQL, PostgreSQL, MongoDB)
โ””โ”€โ”€ middleware/ # 15 built-in middleware modules
include/csilk/ # Public Hierarchical Headers
โ”œโ”€โ”€ core/ # Core internal definitions
โ”œโ”€โ”€ app/ # App API, Admin, Workflow, WAL
โ”œโ”€โ”€ drivers/ # Driver interfaces (AI, Cipher, DB, Perm)
โ”œโ”€โ”€ reflection/ # Reflection engine API
โ”œโ”€โ”€ test/ # OOM simulation test framework
โ””โ”€โ”€ csilk.h # Main entry point (includes all modules)
tests/ # 98+ comprehensive unit tests
examples/ # Functional usage examples

Testing

The project includes a comprehensive test suite. After building, run individual test executables:

./tests/test_context
./tests/test_router
./tests/test_server
# ... and others

Features Legend

Emoji Meaning
๐Ÿš€ Performance / Async I/O
๐Ÿ“ฌ Internal Event Bus (MQ)
๐Ÿ“ˆ Prometheus Metrics
๐Ÿ”ง Middleware / Tooling
๐ŸŒ Networking / Routing
๐Ÿ“ฆ JSON / Data serialization
๐Ÿช Cookie management
๐Ÿ”Œ WebSocket support
๐Ÿ“ก Server-Sent Events (SSE)
๐Ÿ“ค File upload / Multipart
๐Ÿ” URL / Query parsing
โšก Connection keep-alive
๐Ÿ›ก๏ธ Error handling / Security
๐Ÿ” Crypto / Cipher drivers
๐Ÿ“‹ Configuration (YAML)
๐Ÿ— Memory management (Arena)
๐Ÿ—‚๏ธ Reflection engine
๐Ÿค– AI Unified Interface
๐Ÿ” CSRF / CORS / Rate limiting
๐Ÿ“ Documentation (Doxygen)
๐Ÿงต Thread-safe logging
๐Ÿ” Timeouts / Limits
๐ŸŽฏ Per-route middleware
๐ŸŒฒ Radix Tree router
๐Ÿ“ Form URL-encoded parsing
๐Ÿช Session management
๐Ÿ”€ HTTP redirect
๐Ÿ“„ HTTP Range / 206 Partial Content
โœ… Parameter validation

License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

Acknowledgments

  • Inspired by Gin web framework
  • Built upon excellent C libraries: libuv, llhttp, and cJSON