Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
Switchy Web Server
A web server abstraction library providing a unified interface for HTTP server functionality with support for routing, middleware, and multiple backend implementations.
Features
- Server Abstraction: Unified web server interface with pluggable backends
- Routing Support: Define scopes and routes with HTTP method handling
- Request/Response Types: Unified HTTP request and response abstractions
- Query Parsing: Built-in query string parsing with serde support
- CORS Support: Optional CORS middleware configuration
- Compression: Optional response compression support
- OpenAPI Integration: Optional OpenAPI documentation generation
- Multiple Backends: Support for different server implementations (Actix Web)
- Error Handling: Structured error types with HTTP status codes
Installation
Add this to your Cargo.toml:
[]
= {
version = "0.1.0",
= ["actix", "cors", "compress", "openapi"]
}
Usage
Basic Server Setup
use ;
async
Creating Routes and Scopes
use ;
use StatusCode;
Request Handling
use ;
use Deserialize;
async
Path Parameter Extraction
use ;
async
async : )
use Deserialize;
async
Response Types
use ;
use StatusCode;
// JSON responses (require 'serde' feature)
CORS Configuration
use ;
Compression Support
use WebServerBuilder;
Error Handling
use ;
use StatusCode;
async
OpenAPI Integration
use ;
use OpenApi;
API Reference
Core Types
WebServerBuilder- Builder for configuring web serversHttpRequest- Unified HTTP request interfaceHttpResponse- HTTP response builderScope- Route grouping and nestingRoute- Individual route definitionStaticFiles- Static file serving configurationError- HTTP error types with status codes
Extractors
Path<T>- Extract URL path parameters (requiresserdefeature)Query<T>- Extract query parameters (requiresserdefeature)Json<T>- Extract JSON request body (requiresserdefeature)Headers- Extract request headers in a Send-safe wayRequestData- Send-safe wrapper containing commonly needed request dataRequestInfo- Basic request information (method, path, query, remote address)
Request Methods
path()- Get request pathpath_params()- Get all path parameters as a mappath_param(name)- Get a specific path parameter by namequery_string()- Get raw query stringparse_query<T>()- Parse query string into typed structheader(name)- Get header value by namemethod()- Get HTTP methodbody()- Get request body (for simulator backend)cookie(name)- Get cookie value by namecookies()- Get all cookies as a mapremote_addr()- Get remote client address
Response Methods
ok(),not_found(),temporary_redirect(),permanent_redirect()- Common status codesfrom_status_code(),new()- Custom status codeswith_body()- Set response bodywith_location()- Set location headerwith_header()- Add a single headerwith_headers()- Add multiple headerswith_content_type()- Set Content-Type headerjson()- Create JSON response with automatic Content-Type (requiresserdefeature)html()- Create HTML response with automatic Content-Typetext()- Create plain text response with automatic Content-Type
Builder Methods
WebServerBuilder Methods:
with_addr(),with_port()- Server address configurationwith_scope()- Add route scopewith_static_files()- Configure static file servingwith_cors()- Configure CORS (requirescorsfeature)with_compress()- Enable compression (requirescompressfeature)build()- Build the web server
Scope Methods:
new(path)- Create a new scope with a base pathwith_route()- Add a single routewith_routes()- Add multiple routeswith_scope()- Add a nested scopewith_scopes()- Add multiple nested scopesroute(method, path, handler)- Add a route with a specific HTTP methodget(path, handler)- Add a GET routepost(path, handler)- Add a POST routeput(path, handler)- Add a PUT routedelete(path, handler)- Add a DELETE routepatch(path, handler)- Add a PATCH routehead(path, handler)- Add a HEAD route
Route Methods:
new(method, path, handler)- Create a new routewith_handler(method, path, handler)- Create route with handler that supports extractorsget(path, handler)- Create a GET routepost(path, handler)- Create a POST routeput(path, handler)- Create a PUT routedelete(path, handler)- Create a DELETE routepatch(path, handler)- Create a PATCH routehead(path, handler)- Create a HEAD route
Features
Default features: actix, compress, cors, htmx, openapi-all, serde, tls
Available features:
actix- Enable Actix Web backend support (enabled by default)simulator- Enable test simulator backend (for testing without Actix)serde- Enable JSON serialization/deserialization support (enabled by default)cors- Enable CORS middleware support (enabled by default)compress- Enable response compression (enabled by default)htmx- Enable HTMX integration support (enabled by default)static-files- Enable static file serving supporttls- Enable TLS/SSL support (OpenSSL) (enabled by default)openapi- Enable OpenAPI documentation generationopenapi-all- Enable all OpenAPI UI variants (enabled by default)openapi-rapidoc- Enable RapiDoc OpenAPI UIopenapi-redoc- Enable ReDoc OpenAPI UIopenapi-scalar- Enable Scalar OpenAPI UIopenapi-swagger-ui- Enable SwaggerUI OpenAPI UI
Error Types
Error::Http- HTTP errors with status codes and source errors- Built-in constructors for common HTTP status codes
- Automatic conversion from query parsing errors
Examples
This package includes comprehensive examples demonstrating various web server features and patterns. Examples are located in the examples/ directory as standalone Cargo projects.
Prerequisites
- Rust toolchain (see root README)
- Understanding of async Rust
- Basic HTTP knowledge
Example Structure
Each example is a complete Cargo project with:
- Its own
Cargo.tomlwith appropriate dependencies - Comprehensive
README.mdwith usage instructions - Self-contained code demonstrating specific features
- Support for both Actix and Simulator backends
Running Examples
The standalone examples are workspace members and can be run directly:
# Run with default features (simulator)
# Run with Actix backend
Available Examples
Standalone Example Projects
Each example is a complete Cargo project with its own dependencies and comprehensive README:
Basic Handler (basic_handler_standalone/)
- Purpose: Demonstrates RequestData extraction without any serde dependencies
- Run:
cargo run -p switchy_web_server_example_basic_handler_standalone - Features: Simple request handling, multiple extractors, no JSON dependencies
- Full Documentation
JSON Extractor (json_extractor_standalone/)
- Purpose: Shows JSON request/response handling with serde
- Run:
cargo run -p switchy_web_server_example_json_extractor_standalone - Features: Json extractor, optional fields, JSON responses, error handling
- Full Documentation
Query Extractor (query_extractor_standalone/)
- Purpose: Demonstrates query parameter parsing with serde
- Run:
cargo run -p switchy_web_server_example_query_extractor_standalone - Features: Query extractor, optional parameters, type-safe parsing
- Full Documentation
Combined Extractors (combined_extractors_standalone/)
- Purpose: Shows multiple extractors working together
- Run:
cargo run -p switchy_web_server_example_combined_extractors_standalone - Features: Query + RequestData, Json + RequestData combinations, JSON API patterns
- Full Documentation
Directory Examples (With Individual READMEs)
Basic Handler (basic_handler/)
- Purpose: Fundamental handler implementation using RequestData
- Run:
cargo run --example basic_handler --features actix - Shows: Basic request/response handling with the new abstraction layer
Simple GET (simple_get/)
- Purpose: Simple GET endpoint implementation
- Run:
cargo run --example simple_get --features actix - Shows: Basic routing and response generation
Nested GET (nested_get/)
- Purpose: Demonstrates nested route structures
- Run:
cargo run --example nested_get --features actix - Shows: Route organization and scope nesting
From Request Test (from_request_test/)
- Purpose: Testing FromRequest trait implementations
- Shows: Custom extractors and request data extraction
Handler Macro Test (handler_macro_test/)
- Purpose: Testing handler macros and code generation
- Shows: Advanced handler patterns and macro usage
OpenAPI Integration (openapi/)
- Purpose: OpenAPI documentation generation
- Run:
cargo run --example openapi --features "actix,openapi-all" - Shows: API documentation with utoipa integration
Testing Examples
Running Tests
# Test individual examples
# Test the main web_server package
Manual Testing with curl
The standalone examples include detailed curl examples in their individual READMEs. When running with Actix backend:
GET Requests
POST with JSON
Query Parameters
Troubleshooting
Feature Flag Issues
Problem: "trait bound not satisfied" errors
Solution: Ensure correct feature flags are enabled (actix or simulator)
Port Conflicts
Problem: "address already in use"
Solution: Change port in example or kill existing process with lsof -ti:8080 | xargs kill
Compilation Errors
Problem: Missing traits or types Solution: Check feature dependencies and ensure all required features are enabled
Current Architecture Limitations
The web server abstraction currently requires feature flags to select between Actix and Simulator backends. This is a known limitation that will be addressed in future versions.
Examples must use conditional compilation:
#[cfg(feature = "actix")]for Actix-specific code#[cfg(feature = "simulator")]for test simulator code
Future versions will provide a unified API that removes this requirement.
Migration Guide
From Raw Actix Web
Handler Changes
- Replace
HttpRequestwithRequestDatafor Send-safety - Use handler macros instead of manual implementations
- Extractors remain mostly the same but work through the abstraction layer
Route Registration
// Before (raw Actix)
new.route
// After (Switchy abstraction)
new.with_route
Dependencies
Core dependencies:
switchy_http_models- HTTP types and status codesserde-querystring- Query string parsingswitchy_web_server_core- Core server functionalitybytes- Efficient byte buffer handlingfutures- Async runtime utilities
Optional dependencies (feature-gated):
switchy_web_server_cors- CORS middleware (withcorsfeature)actix-web- Actix Web server backend (withactixfeature)actix-cors- Actix CORS support (withcorsfeature)actix-htmx- HTMX integration (withhtmxfeature)serde_json- JSON serialization (withserdefeature)utoipa- OpenAPI specification support (withopenapifeature)utoipa-swagger-ui,utoipa-rapidoc,utoipa-redoc,utoipa-scalar- OpenAPI UI variants (with respectiveopenapi-*features)