Expand description
§MockForge HTTP
HTTP/REST API mocking library for MockForge.
This crate provides HTTP-specific functionality for creating mock REST APIs, including OpenAPI integration, request validation, AI-powered response generation, and management endpoints.
§Overview
MockForge HTTP enables you to:
- Serve OpenAPI specs: Automatically generate mock endpoints from OpenAPI/Swagger
- Validate requests: Enforce schema validation with configurable modes
- AI-powered responses: Generate intelligent responses using LLMs
- Management API: Real-time monitoring, configuration, and control
- Request logging: Comprehensive HTTP request/response logging
- Metrics collection: Track performance and usage statistics
- Server-Sent Events: Stream logs and metrics to clients
§Quick Start
§Basic HTTP Server from OpenAPI
use mockforge_http::build_router;
use mockforge_core::{ValidationOptions, FailureConfig};
use axum::Router;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Build router from OpenAPI specification
let router = build_router(
Some("./api-spec.json".to_string()),
Some(ValidationOptions::enforce()),
None,
).await;
// Start the server
let addr = "0.0.0.0:3000".parse()?;
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, router).await?;
Ok(())
}§With Management API
Enable real-time monitoring and configuration:
use mockforge_http::{management_router, ManagementState, ServerStats};
use std::sync::Arc;
use tokio::sync::RwLock;
// Create management state
let stats = Arc::new(RwLock::new(ServerStats::default()));
let state = ManagementState::new(stats);
// Build management router
let mgmt_router = management_router(state);
// Mount under your main router
let app = axum::Router::new()
.nest("/__mockforge", mgmt_router);§AI-Powered Responses
Generate intelligent responses based on request context:
use mockforge_http::{AiResponseConfig, process_response_with_ai};
use mockforge_data::RagConfig;
let ai_config = AiResponseConfig {
enabled: true,
rag_config: RagConfig {
provider: "openai".to_string(),
model: "gpt-3.5-turbo".to_string(),
api_key: Some("sk-...".to_string()),
..Default::default()
},
prompt: "Generate realistic user data".to_string(),
schema: None,
};
// AI will generate contextual response
let response = process_response_with_ai(&ai_config, /* request_data */).await?;§Key Features
§OpenAPI Integration
- Automatic endpoint generation from specs
- Request/response validation
- Schema-based mock data generation
§Management & Monitoring
management: REST API for server control and monitoringmanagement_ws: WebSocket API for real-time updatessse: Server-Sent Events for log streamingrequest_logging: Comprehensive request/response loggingmetrics_middleware: Performance metrics collection
§Advanced Features
ai_handler: AI-powered response generationauth: Authentication and authorizationchain_handlers: Multi-step request workflowslatency_profiles: Configurable latency simulationreplay_listing: Fixture management
§Middleware
MockForge HTTP includes several middleware layers:
- Request Tracing: [
http_tracing_middleware] - Distributed tracing integration - Metrics Collection:
metrics_middleware- Prometheus-compatible metrics - Operation Metadata:
op_middleware- OpenAPI operation tracking
§Management API Endpoints
When using the management router, these endpoints are available:
GET /health- Health checkGET /stats- Server statisticsGET /logs- Request logs (SSE stream)GET /metrics- Performance metricsGET /fixtures- List available fixturesPOST /config/*- Update configuration
§Examples
See the examples directory for complete working examples.
§Related Crates
mockforge-core: Core mocking functionalitymockforge-data: Synthetic data generationmockforge-plugin-core: Plugin development
§Documentation
Re-exports§
pub use ai_handler::process_response_with_ai;pub use ai_handler::AiResponseConfig;pub use ai_handler::AiResponseHandler;pub use management::management_router;pub use management::ManagementState;pub use management::MockConfig;pub use management::ServerConfig;pub use management::ServerStats;pub use management_ws::ws_management_router;pub use management_ws::MockEvent;pub use management_ws::WsManagementState;pub use metrics_middleware::collect_http_metrics;pub use http_tracing_middleware::http_tracing_middleware;pub use coverage::calculate_coverage;pub use coverage::CoverageReport;pub use coverage::MethodCoverage;pub use coverage::RouteCoverage;
Modules§
- ai_
handler - AI-powered response handler for HTTP requests
- auth
- Authentication middleware for MockForge HTTP server
- chain_
handlers - Chain management HTTP handlers for MockForge
- coverage
- Mock Coverage Tracking
- http_
tracing_ middleware - HTTP tracing middleware for distributed tracing
- latency_
profiles - Operation-aware latency/failure profiles (per operationId and per tag).
- management
- management_
ws - metrics_
middleware - HTTP metrics collection middleware
- middleware
- HTTP middleware modules
- op_
middleware - Middleware/utilities to apply latency/failure and overrides per operation.
- rag_
ai_ generator - RAG-based AI generator implementation
- replay_
listing - Record/replay listing for HTTP/gRPC/WS fixtures.
- request_
logging - HTTP request logging middleware
- sse
- Server Sent Events (SSE) support for MockForge
Structs§
- Http
Server State - Shared state for tracking OpenAPI routes
- Route
Info - Route info for storing in state
Functions§
- build_
router - Build the base HTTP router, optionally from an OpenAPI spec.
- build_
router_ with_ auth - Build the base HTTP router with authentication support
- build_
router_ with_ auth_ and_ latency - Build the base HTTP router with authentication and latency support
- build_
router_ with_ chains - Build the base HTTP router with chaining support
- build_
router_ with_ chains_ and_ multi_ tenant - Build the base HTTP router with chaining and multi-tenant support
- build_
router_ with_ latency - Build the base HTTP router with latency injection support
- build_
router_ with_ multi_ tenant - Build the base HTTP router with multi-tenant workspace support
- serve_
router - Serve a provided router on the given port.
- start
- Backwards-compatible start that builds + serves the base router.
- start_
with_ auth_ and_ injectors - Start HTTP server with authentication and injectors support
- start_
with_ auth_ and_ latency - Start HTTP server with authentication and latency support
- start_
with_ latency - Start HTTP server with latency injection support