Gearbox
A lightweight, opinionated Rust web framework with automatic dependency injection.
Features
- Dependency Injection - Declare dependencies with
#[inject]and let Gearbox wire everything together - Auto-Registration - Services (Cogs) are automatically discovered and registered at startup
- Dependency Resolution - Topological sorting ensures services are initialized in the correct order
- Configuration System - Load config from TOML files and environment variables with relaxed binding
- Route Macros - Define HTTP handlers with
#[get],#[post], etc. and automatic parameter injection - PostgreSQL Support -
#[derive(PgEntity)]generates CRUD operations,pg_queries!for custom SQL - REST API Generation -
#[derive(Crud)]generates complete REST endpoints with pagination - Built on Axum - Leverages the battle-tested Axum web framework under the hood
Quick Start
Add Gearbox to your Cargo.toml:
[]
= "0.1"
= { = "1", = ["rt-multi-thread", "macros"] }
# For PostgreSQL support:
# gearbox-rs = { version = "0.1", features = ["postgres"] }
Hello World Example
use *;
use Arc;
// Helper function for default message
// Define a service (Cog)
// Define a route that uses the service
async
// Start the application
Run with:
Visit http://localhost:8080/hello/world to see: Hello, world!
Core Concepts
Cogs (Services)
A Cog is Gearbox's term for a service or component. Use the #[cog] macro to define one:
Field attributes:
#[inject]- Inject anArc<T>from the service registry#[config]- Load from configuration (requiresCogConfigimpl)#[default(fn)]- Initialize via a sync function#[default_async(fn)]- Initialize via an async function- No attribute - Uses
Default::default()
Configuration
Define configuration structs with #[cog_config]:
Create a config.toml:
[]
= 8080
= "info"
[]
= "postgres://localhost/mydb"
= 10
Override with environment variables:
GEARBOX_DATABASE_URL=postgres://prod/mydb
GEARBOX_DATABASE_MAXCONNECTIONS=50
GEARBOX_GEARBOXAPP_HTTPPORT=3000
Gearbox uses relaxed binding - all of these match max_connections:
max-connections(TOML kebab-case)max_connections(TOML snake_case)MAXCONNECTIONS(env var)
Routes
Define HTTP handlers with route macros:
async
async
async
Available macros: #[get], #[post], #[put], #[delete], #[patch]
Arc<T> parameters are automatically transformed to use Gearbox's Inject<T> extractor. Other Axum extractors (Json, Path, Query, etc.) work as normal.
PostgreSQL Entities
Generate repository operations with #[derive(PgEntity)]:
// Generated methods on PgClient:
// - create(entity) -> INSERT
// - update(entity) -> UPDATE
// - upsert(entity) -> INSERT ... ON CONFLICT
// - find_by_id(id) -> SELECT
// - find_by_ids(ids) -> SELECT ... IN
// - find_page(limit, offset) -> SELECT with pagination
// - exists(id) -> SELECT EXISTS
// - count() -> SELECT COUNT
// - delete(id) -> DELETE
// - create_batch(entities) -> batch INSERT
// - upsert_batch(entities) -> batch UPSERT
Custom Queries
Define custom SQL queries with pg_queries!:
use pg_queries;
pg_queries!
Usage - import the PgQueries trait:
use cratePgQueries;
let user = client.find_user_by_email.await?;
let count = client.count_users_by_role.await?;
let deleted = client.deactivate_user.await?; // returns bool
Return type mapping:
| Return Type | Behavior |
|---|---|
Option<T> |
fetch_optional - returns None if no row |
Vec<T> |
fetch_all - returns all matching rows |
T (struct) |
fetch_one - errors if no row found |
i64, String, etc. |
query_scalar - single column value |
bool |
execute - true if rows_affected > 0 |
u64 |
execute - returns rows_affected |
| (none) | execute - returns () |
Complex Joins
Use custom structs to represent JOIN results:
// Define a struct for the join result
pg_queries!
The struct field names must match the column aliases in your SQL query. Use AS to rename columns from joins to avoid conflicts and match your struct fields.
REST API Generation with Crud
Generate complete REST endpoints with #[derive(Crud)]:
This generates:
DTOs:
UserCreate- For POST requests (excludesid,created_at)UserUpdate- For PATCH requests (all fields optional)UserQuery- Query parameters for paginationUserResponse- For responses (excludespassword_hash)
Routes:
| Method | Path | Description |
|---|---|---|
| GET | /users |
List with pagination |
| GET | /users/{id} |
Get single entity |
| POST | /users |
Create new entity |
| PUT | /users/{id} |
Full update |
| PATCH | /users/{id} |
Partial update |
| DELETE | /users/{id} |
Delete entity |
Field Attributes
| Attribute | Description |
|---|---|
#[auto_generated] |
DB generates this (UUID, serial). Excluded from create/update DTOs |
#[readonly] |
Only in responses (e.g., created_at). Excluded from create/update |
#[writeonly] |
Only in create/update (e.g., password_hash). Excluded from responses |
Query Examples
# Paginate results
&offset=0
For custom filtering, use pg_queries! with a custom route handler.
Struct-Level Options
// Only GET endpoints
// No POST endpoint
// No DELETE endpoint
Project Structure
gearbox-rs/
├── core/ # Core framework (Hub, Config, DI, routing)
├── macros/ # Procedural macros (#[cog], #[get], etc.)
├── pg/ # PostgreSQL integration
└── examples/ # Example applications
License
MIT