{"id":16556819,"url":"https://github.com/dyatlovk/ws_server","last_synced_at":"2026-06-01T04:31:56.453Z","repository":{"id":203647004,"uuid":"705435605","full_name":"dyatlovk/ws_server","owner":"dyatlovk","description":"Web server for C++","archived":false,"fork":false,"pushed_at":"2025-09-15T18:04:33.000Z","size":935,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-15T20:12:33.332Z","etag":null,"topics":["cpp","httpserver","linux-server","webserver"],"latest_commit_sha":null,"homepage":"","language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dyatlovk.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2023-10-16T02:00:16.000Z","updated_at":"2025-09-15T18:04:31.000Z","dependencies_parsed_at":null,"dependency_job_id":"ad9946bf-62c7-46f2-a8d6-2967eb7fcd56","html_url":"https://github.com/dyatlovk/ws_server","commit_stats":null,"previous_names":["dyatlovk/ws_server"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/dyatlovk/ws_server","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dyatlovk%2Fws_server","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dyatlovk%2Fws_server/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dyatlovk%2Fws_server/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dyatlovk%2Fws_server/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dyatlovk","download_url":"https://codeload.github.com/dyatlovk/ws_server/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dyatlovk%2Fws_server/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33760645,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-01T02:00:06.963Z","response_time":115,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cpp","httpserver","linux-server","webserver"],"created_at":"2024-10-11T20:05:50.323Z","updated_at":"2026-06-01T04:31:56.447Z","avatar_url":"https://github.com/dyatlovk.png","language":"C++","funding_links":[],"categories":[],"sub_categories":[],"readme":"# WS Server\n\nA modern, high-performance HTTP web server library written in C++20, designed for building scalable web applications and APIs.\n\n## Table of Contents\n\n- [Features](#features)\n- [Quick Start](#quick-start)\n- [Examples](#examples)\n- [Installation](#installation)\n- [API Reference](#api-reference)\n- [Advanced Usage](#advanced-usage)\n- [Architecture](#architecture)\n- [Development](#development)\n- [Troubleshooting](#troubleshooting)\n- [License](#license)\n- [Support](#support)\n\n## Features\n\n- **HTTP/1.1 Support**: Full HTTP/1.1 protocol implementation with keep-alive connections\n- **Modern C++20**: Leverages the latest C++ features for performance and safety\n- **Epoll-based I/O**: Efficient event-driven I/O using Linux epoll for high concurrency\n- **Routing System**: Flexible URL routing with parameter extraction and regex support\n- **Middleware Support**: Modular middleware architecture for request/response processing\n- **Static File Serving**: Built-in static file server with MIME type detection\n- **JSON Support**: Native JSON request/response handling\n- **Thread Pool**: Asynchronous request processing with configurable thread pool\n- **Socket Abstraction**: TCP and Unix domain socket support\n- **MVC Architecture**: Model-View-Controller pattern support for structured applications\n- **Comprehensive Logging**: Colored, timestamped logging system with multiple levels and fmt-style formatting\n- **Comprehensive Testing**: Full test suite with unit tests and benchmarks\n\n## Quick Start\n\n### Basic HTTP Server\n```cpp\n#include \u003chttp/server.h++\u003e\n#include \u003chttp/options.h++\u003e\n\nint main() {\n    auto options = http::options({3044, \"127.0.0.1\", \"My Server\", \"/public\"});\n    http::server app(\u0026options);\n\n    http::router router;\n    router.add(\"/\", http::request::methods::Get,\n        [](const http::request *req, http::response *res) {\n            res-\u003ewith_body(\"Hello, World!\");\n        });\n\n    app.with_routers(\u0026router);\n    return app.listen();\n}\n```\n\n## Examples\n\nThe project includes several comprehensive examples:\n\n* **[Basic Server](./examples/basic/)** - Minimal HTTP server setup\n* **[HTTP Server](./examples/http_server/)** - Full-featured HTTP server with routing, JSON API, and static files\n* **[MVC Application](./examples/mvc/)** - Complete MVC web application with frontend/backend separation\n* **[Logging Demo](./examples/logging_demo/)** - Comprehensive demonstration of the logging system features\n\n## Installation\n\n### Requirements\n- **Git** - Version control\n- **CMake 3.26+** - Build system (as required by CMakeLists.txt)\n- **C++20 Compiler** - GCC 11+ or Clang 12+\n- **Linux** - Currently supports Linux with epoll\n\n### Build Instructions\n\n1. **Clone the repository:**\n```bash\ngit clone git@github.com:dyatlovk/ws_server.git\ncd ws_server\n```\n\n2. **Configure and build (Debug):**\n```bash\ncmake --preset=makefile-x86_64-linux-debug\ncmake --build --preset=debug-build-linux -j$(nproc)\n```\n\n3. **Configure and build (Release):**\n```bash\ncmake --preset=makefile-x86_64-linux-release\ncmake --build --preset=release-build-linux -j$(nproc)\n```\n\n### Build Options\n\n| Option               | Debug         | Release      | Description                    |\n| -------------------- | ------------- | ------------ | ------------------------------ |\n| CMAKE_BUILD_TYPE     | Debug         | MinSizeRel   | Build optimization level       |\n| SRV_BUILD_EXAMPLES   | On            | On           | Build example applications     |\n| SRV_BUILD_BENCHMARKS | Off           | On           | Build performance benchmarks  |\n| SRV_BUILD_TESTS      | On            | Off          | Build unit test suite         |\n\n### Running Tests\n\n```bash\n# Build with tests enabled (debug mode)\ncmake --preset=makefile-x86_64-linux-debug\ncmake --build --preset=debug-build-linux -j$(nproc)\n\n# Run the test suite\n./build/makefile-x86_64-linux-debug/tests/server_test\n```\n\n### Running Benchmarks\n\n```bash\n# Build with benchmarks enabled (release mode)\ncmake --preset=makefile-x86_64-linux-release\ncmake --build --preset=release-build-linux -j$(nproc)\n\n# Run benchmarks\n./build/makefile-x86_64-linux-release/benchmarks/response/benchmark_response\n./build/makefile-x86_64-linux-release/benchmarks/router/benchmark_router\n```\n\n### Running Examples\n\n```bash\n# Examples are built with both debug and release configurations\n# Run basic example\n./build/makefile-x86_64-linux-debug/examples/basic/basic_example\n\n# Run HTTP server example\n./build/makefile-x86_64-linux-debug/examples/http_server/http_server\n\n# Run MVC example\n./build/makefile-x86_64-linux-debug/examples/mvc/mvc\n\n# Run logging system demonstration\n./build/makefile-x86_64-linux-debug/examples/logging_demo/logging_demo\n```\n\n### Quick Verification\n\nAfter building, verify everything works:\n\n```bash\n# 1. Verify tests pass\n./build/makefile-x86_64-linux-debug/tests/server_test --gtest_filter=\"*headers*\"\n\n# 2. Run a simple server test (in background, then test with curl)\n./build/makefile-x86_64-linux-debug/examples/basic/basic_example \u0026\nSERVER_PID=$!\nsleep 1\ncurl http://127.0.0.1:3044  # Should return \"index\"\nkill $SERVER_PID\n\n# 3. Check benchmark runs without errors\n./build/makefile-x86_64-linux-release/benchmarks/response/benchmark_response\n\n# 4. Test logging system\n./build/makefile-x86_64-linux-debug/examples/logging_demo/logging_demo\n```\n\n## API Reference\n\n### Server Configuration\n\n```cpp\n// Server options\nhttp::options options({\n    3044,               // Port\n    \"127.0.0.1\",       // Host\n    \"My Server\",       // Server name\n    \"/public\"          // Static files directory\n});\n\nhttp::server app(\u0026options);\n```\n\n### Routing\n\n```cpp\nhttp::router router;\n\n// Simple route\nrouter.add(\"/\", http::request::methods::Get, handler);\n\n// Multiple HTTP methods\nrouter.add(\"/api/data\", {http::request::methods::Get, http::request::methods::Post}, handler);\n\n// Route parameters with regex\nrouter.add(\"/user/\\\\d+\", http::request::methods::Get, user_handler);\nrouter.add(\"/blog/\\\\D+\", http::request::methods::Get, blog_handler);\n```\n\n### Request Handling\n\n```cpp\nauto handler = [](http::request *req, http::response *res) {\n    // Access request method\n    auto method = req-\u003ereq.method;\n\n    // Access URI and parameters\n    auto uri = req-\u003ereq.uri;\n    auto params = req-\u003ereq.params; // Extracted from regex routes\n\n    // HTTP version\n    auto version = req-\u003ereq.http_ver;\n};\n```\n\n### Response Methods\n\n```cpp\n// Text response\nres-\u003ewith_body(\"Hello, World!\");\n\n// JSON response\nminiJson::Json json = miniJson::Json::_object{{\"key\", \"value\"}};\nres-\u003ewith_json(\u0026json);\n\n// File response\nres-\u003ewith_view(\"/index.html\");\n\n// Redirect\nres-\u003ewith_redirect(\"/new-location\");\n\n// Headers\nres-\u003ewith_header(\"Content-Type\", \"application/json\");\nres-\u003ewith_added_header(\"X-Custom\", \"value\");\n\n// Status codes\nres-\u003ewith_status(404, \"Not Found\");\n```\n\n### Logging System\n\nThe server includes a comprehensive logging system with colored output, timestamps, and multiple log levels:\n\n```cpp\n#include \u003cutils/logger.h++\u003e\n\n// Basic logging with different levels\nLOG_DEBUG(\"Detailed diagnostic information: {}\", debug_info);\nLOG_INFO(\"General application flow: {}\", status);\nLOG_WARN(\"Warning condition: {}\", warning_msg);\nLOG_ERROR(\"Error occurred: {}\", error_msg);\n\n// Configure log level filtering\nutils::Logger::set_level(utils::LogLevel::INFO);  // Hide DEBUG messages\nutils::Logger::set_level(utils::LogLevel::WARN);  // Hide DEBUG and INFO\nutils::Logger::set_level(utils::LogLevel::ERROR); // Only show ERROR\n\n// Advanced formatting with fmt-style syntax\nLOG_INFO(\"User {} has {} unread messages\", username, count);\nLOG_DEBUG(\"Server stats: CPU={:.1f}%, Memory={:.2f}GB\", cpu_usage, memory_gb);\nLOG_ERROR(\"Database connection failed: host={}, port={}, timeout={}ms\",\n          db_host, db_port, timeout);\n```\n\n#### Log Levels and Colors\n\n| Level | Color  | Description | Output Stream |\n|-------|--------|-------------|---------------|\n| DEBUG | Cyan   | Detailed diagnostic information | stdout |\n| INFO  | Green  | General information about program execution | stdout |\n| WARN  | Yellow | Warning conditions that should be noted | stderr |\n| ERROR | Red    | Error conditions that indicate problems | stderr |\n\n#### Integration with HTTP Server\n\nThe logging system is already integrated throughout the HTTP server components:\n\n```cpp\n// Server startup and shutdown\nLOG_INFO(\"Server starting on {}:{}\", host, port);\nLOG_ERROR(\"Failed to initialize epoll: {}\", e.what());\nLOG_INFO(\"Server is shutting down\");\n\n// Socket operations (automatically logged)\nLOG_DEBUG(\"Creating inet_socket for {}:{}\", host, port);\nLOG_INFO(\"Opening socket for {}:{} (domain={}, type={})\", host, port, domain, type);\nLOG_ERROR(\"Failed to create socket: {}\", std::strerror(errno));\n\n// Connection handling\nLOG_INFO(\"Accepted connection from client (fd={})\", peer);\nLOG_DEBUG(\"Reading from connection fd={}, bufSize={}\", conn, bufSize);\n```\n\n## Advanced Usage\n\n### MVC Architecture\n\nThe server supports Model-View-Controller patterns for larger applications:\n\n```cpp\n// Controller class\nclass BlogController {\npublic:\n    auto list(http::request *req, http::response *res) -\u003e http::response {\n        res-\u003ewith_json(\u0026blog_list);\n        return *res;\n    }\n\n    auto entry(http::request *req, http::response *res) -\u003e http::response {\n        auto params = req-\u003ereq.params;\n        if (!params.empty()) {\n            int id = std::atoi(params[0].c_str());\n            // Load blog entry by ID\n        }\n        return *res;\n    }\n};\n\n// Usage\nBlogController blog;\nrouter.add(\"/blog\", method::Get,\n    std::bind(\u0026BlogController::list, \u0026blog, std::placeholders::_1, std::placeholders::_2));\n```\n\n### Static File Serving\n\nThe server automatically serves static files from the configured public directory:\n\n- Automatic MIME type detection\n- Efficient file streaming\n- Support for common web assets (HTML, CSS, JS, images)\n- Configurable document root\n\n### Performance Features\n\n- **Epoll I/O Multiplexing**: Handle thousands of concurrent connections\n- **Thread Pool**: Configurable worker threads for request processing\n- **Zero-Copy Operations**: Efficient memory management\n- **Connection Keep-Alive**: HTTP/1.1 persistent connections\n\n### Logging and Debugging\n\nThe server provides comprehensive logging capabilities for development and production:\n\n```cpp\n// Development logging - show all messages\n#ifdef DEBUG\n    utils::Logger::set_level(utils::LogLevel::DEBUG);\n#else\n    utils::Logger::set_level(utils::LogLevel::INFO);\n#endif\n\n// Production logging with structured messages\nLOG_INFO(\"Request processed: method={}, path='{}', status={}, duration={}ms\",\n         method, path, status_code, duration);\n\n// Error handling with context\ntry {\n    // ... server operations\n} catch (const std::exception\u0026 e) {\n    LOG_ERROR(\"Server error: {}\", e.what());\n}\n```\n\n#### Best Practices for Logging\n\n1. **Use appropriate log levels**:\n   - `DEBUG`: Detailed diagnostic info for development\n   - `INFO`: General application flow and important events\n   - `WARN`: Recoverable issues that should be noted\n   - `ERROR`: Serious problems that need attention\n\n2. **Include context in messages**:\n   ```cpp\n   LOG_ERROR(\"Failed to process request: client={}, path='{}', error='{}'\",\n             client_id, request_path, error_msg);\n   ```\n\n3. **Be mindful of sensitive data** - never log passwords or tokens\n\n4. **Use structured logging for metrics**:\n   ```cpp\n   LOG_INFO(\"Performance metrics: requests={}, avg_time={}ms, errors={}\",\n            request_count, avg_response_time, error_count);\n   ```\n\n## Architecture\n\n### Core Components\n\n- **HTTP Parser**: RFC-compliant HTTP message parsing\n- **Socket Layer**: Abstraction over TCP and Unix domain sockets\n- **Epoll Engine**: Event-driven I/O for scalability\n- **Router**: URL pattern matching and parameter extraction\n- **Middleware Stack**: Pluggable request/response processing\n- **Thread Pool**: Asynchronous task execution\n- **Logging System**: Colored, timestamped logging with multiple levels and fmt-style formatting\n\n### Dependencies\n\n- **fmt**: Modern C++ formatting library\n- **MiniJSON**: Lightweight JSON parsing and generation\n- **Reflex**: Regular expression engine for routing\n\n## Development\n\n### Project Structure\n\n```\n├── src/                    # Core library source code\n│   ├── http/              # HTTP protocol implementation\n│   ├── io/                # I/O abstractions (sockets, epoll)\n│   ├── stl/               # STL extensions\n│   └── utils/             # Utility classes (logging, thread pool)\n├── examples/              # Example applications\n├── tests/                 # Unit test suite\n├── benchmarks/            # Performance benchmarks\n└── vendor/                # Third-party dependencies\n```\n\n### Contributing\n\n1. **Code Style**: Follow modern C++20 conventions\n2. **Testing**: Add tests for new features\n3. **Documentation**: Update README and code comments\n4. **Performance**: Consider performance implications\n\n### Complete Development Workflow\n\n```bash\n# 1. Setup development environment\ngit clone git@github.com:dyatlovk/ws_server.git\ncd ws_server\n\n# 2. Configure for development (debug + tests)\ncmake --preset=makefile-x86_64-linux-debug\n\n# 3. Build everything\ncmake --build --preset=debug-build-linux -j$(nproc)\n\n# 4. Run tests to ensure everything works\n./build/makefile-x86_64-linux-debug/tests/server_test\n\n# 5. Make your changes...\n\n# 6. Rebuild and test\ncmake --build --preset=debug-build-linux -j$(nproc)\n./build/makefile-x86_64-linux-debug/tests/server_test\n\n# 7. Test performance impact (optional)\ncmake --preset=makefile-x86_64-linux-release\ncmake --build --preset=release-build-linux -j$(nproc)\n./build/makefile-x86_64-linux-release/benchmarks/response/benchmark_response\n\n# 8. Test examples still work\n./build/makefile-x86_64-linux-debug/examples/basic/basic_example\n```\n\n### Testing\n\nThe project includes comprehensive tests covering:\n\n- HTTP parsing and generation\n- Socket operations\n- Routing functionality\n- Request/response handling\n- Error conditions\n\n### Benchmarking\n\nPerformance benchmarks are available for:\n\n- Response generation speed\n- Router matching performance\n- Memory usage patterns\n- Concurrency handling\n\n## Troubleshooting\n\n### Build Issues\n\n**CMake version mismatch:**\n```bash\n# Ensure you have CMake 3.26+\ncmake --version\n\n# On Ubuntu/Debian, you might need to install from Kitware's repository\n# if your distribution's CMake is too old\n```\n\n**Missing dependencies:**\n```bash\n# Ensure you have a C++20 compatible compiler\ng++ --version  # Should be GCC 11+\nclang++ --version  # Should be Clang 12+\n\n# On Ubuntu/Debian:\nsudo apt update\nsudo apt install build-essential cmake git\n```\n\n**Build preset not found:**\n```bash\n# List available presets\ncmake --list-presets\n\n# If presets are not working, try manual configuration\nmkdir -p build/manual\ncd build/manual\ncmake ../.. -DCMAKE_BUILD_TYPE=Debug -DSRV_BUILD_TESTS=ON\nmake -j$(nproc)\n```\n\n### Runtime Issues\n\n**Permission denied when running executables:**\n```bash\n# Make sure executables have execute permissions\nchmod +x ./build/makefile-x86_64-linux-debug/tests/server_test\n```\n\n**Port already in use:**\n```bash\n# Check if port is already in use\nsudo netstat -tulpn | grep :3044\n\n# Kill process using the port\nsudo lsof -ti:3044 | xargs sudo kill -9\n```\n\n**Library linking errors:**\n```bash\n# Ensure all dependencies are built\nmake clean\ncmake --build --preset=debug-build-linux -j$(nproc)\n```\n\n### Testing Issues\n\n**Tests failing:**\n```bash\n# Run specific test categories\n./build/makefile-x86_64-linux-debug/tests/server_test --gtest_filter=\"*HttpParser*\"\n\n# Run in verbose mode for debugging\n./build/makefile-x86_64-linux-debug/tests/server_test --gtest_verbose\n```\n\n**Performance issues:**\n```bash\n# Run in release mode for better performance\ncmake --preset=makefile-x86_64-linux-release\ncmake --build --preset=release-build-linux -j$(nproc)\n./build/makefile-x86_64-linux-release/examples/basic/basic_example\n```\n\n### Logging Issues\n\n**Too verbose logging in production:**\n```bash\n# Set appropriate log level to reduce output\nutils::Logger::set_level(utils::LogLevel::WARN);  # Only warnings and errors\nutils::Logger::set_level(utils::LogLevel::ERROR); # Only errors\n```\n\n**Missing log output:**\n```bash\n# Ensure log level allows your messages\nutils::Logger::set_level(utils::LogLevel::DEBUG);  # Show all messages\n\n# Check if you're using the correct macros\nLOG_INFO(\"This message will appear\");  # Correct\nfmt::println(\"This bypasses logging system\");  # Bypasses logging\n```\n\n**Log colors not showing:**\n```bash\n# Ensure terminal supports ANSI colors\necho $TERM  # Should show color-capable terminal like xterm-256color\n\n# Test color support\n./build/makefile-x86_64-linux-debug/examples/logging_demo/logging_demo\n```\n\n## License\n\nThis project is open source. Please check the repository for license details.\n\n## Support\n\n- **Issues**: Report bugs and feature requests on GitHub\n- **Documentation**: Additional examples in the `examples/` directory\n- **Community**: Contributions and feedback welcome\n\n---\n\n**Note**: This server is designed for Linux environments and requires epoll support. Windows and macOS support may be added in future versions.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdyatlovk%2Fws_server","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdyatlovk%2Fws_server","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdyatlovk%2Fws_server/lists"}