Providing complete Rust hexagonal Actix-web skeleton
I'm producing a full Rust project skeleton with hexagonal architecture, featuring domain traits, SQLx compile-time checked queries, async-trait for repository interfaces, Actix-web HTTP adapters, and a minimal main.rs showing server setup and dependency injection using Arc wrappers. The Cargo.toml specifies exact dependencies and features for Tokio runtime with Rustls TLS and Postgres backend. The domain models, repository traits, application services, database adapter, HTTP handlers, error mapping, and JSON serialization align with pure core logic separated from infrastructure, illustrating a clean, compilable boilerplate.
Below is a small but complete hexagonal (ports & adapters) boilerplate for Actix‑web using sqlx with compile‑time checked SQL. The core/business logic lives in pure Rust traits and structs, independent of HTTP. Actix handlers and the SQLx repository are adapters.
.
├── Cargo.toml
└── src
├── main.rs
├── domain
│ ├── mod.rs
│ ├── user.rs
│ ├── error.rs
│ └── ports.rs
├── application
│ ├── mod.rs
│ └── user_service.rs
└── infrastructure
├── mod.rs
├── db.rs
└── http
├── mod.rs
├── handlers.rs
└── routes.rs
Cargo.toml
[package]
name = "hex_actix_sqlx"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
uuid = { version = "1", features = ["v4", "serde"] }
thiserror = "1"
async-trait = "0.1"
sqlx = { version = "0.7", default-features = false, features = [
"runtime-tokio-rustls",
"postgres",
"macros",
"uuid",
"chrono"
] }
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
env_logger = "0.11"
log = "0.4"
src/domain/mod.rs
pub mod user;
pub mod error;
pub mod ports;
src/domain/user.rs
use serde::{Deserialize, Serialize};
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: Uuid,
pub name: String,
pub email: String,
}
src/domain/error.rs
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DomainError {
#[error("entity not found")]
NotFound,
#[error("entity already exists")]
AlreadyExists,
#[error("validation error: {0}")]
Validation(String),
#[error("unexpected error: {0}")]
Unexpected(String),
}
src/domain/ports.rs
use async_trait::async_trait;
use uuid::Uuid;
use crate::domain::user::User;
use crate::domain::error::DomainError;
#[async_trait]
pub trait UserRepository: Send + Sync {
async fn create(&self, user: &User) -> Result<User, DomainError>;
async fn get(&self, id: Uuid) -> Result<User, DomainError>;
async fn list(&self) -> Result<Vec<User>, DomainError>;
}
src/application/mod.rs
pub mod user_service;
src/application/user_service.rs
use uuid::Uuid;
use crate::domain::ports::UserRepository;
use crate::domain::user::User;
use crate::domain::error::DomainError;
pub struct UserService<R: UserRepository> {
repo: R,
}
impl<R: UserRepository> UserService<R> {
pub fn new(repo: R) -> Self {
Self { repo }
}
pub async fn create_user(&self, name: String, email: String) -> Result<User, DomainError> {
if name.is_empty() {
return Err(DomainError::Validation("name cannot be empty".into()));
}
if email.is_empty() {
return Err(DomainError::Validation("email cannot be empty".into()));
}
let user = User {
id: Uuid::new_v4(),
name,
email,
};
self.repo.create(&user).await
}
pub async fn get_user(&self, id: Uuid) -> Result<User, DomainError> {
self.repo.get(id).await
}
pub async fn list_users(&self) -> Result<Vec<User>, DomainError> {
self.repo.list().await
}
}
src/infrastructure/mod.rs
pub mod db;
pub mod http;
src/infrastructure/db.rs
use async_trait::async_trait;
use sqlx::{PgPool, FromRow};
use uuid::Uuid;
use crate::domain::{error::DomainError, ports::UserRepository, user::User};
#[derive(FromRow)]
struct UserRow {
id: Uuid,
name: String,
email: String,
}
pub struct SqlxUserRepository {
pool: PgPool,
}
impl SqlxUserRepository {
pub fn new(pool: PgPool) -> Self {
Self { pool }
}
}
#[async_trait]
impl UserRepository for SqlxUserRepository {
async fn create(&self, user: &User) -> Result<User, DomainError> {
let created = sqlx::query_as!(
UserRow,
r#"
INSERT INTO users (id, name, email)
VALUES ($1, $2, $3)
RETURNING id, name, email
"#,
user.id,
user.name,
user.email
)
.fetch_one(&self.pool)
.await
.map_err(|e| DomainError::Unexpected(e.to_string()))?;
Ok(User {
id: created.id,
name: created.name,
email: created.email,
})
}
async fn get(&self, id: Uuid) -> Result<User, DomainError> {
let row = sqlx::query_as!(
UserRow,
r#"SELECT id, name, email FROM users WHERE id = $1"#,
id
)
.fetch_optional(&self.pool)
.await
.map_err(|e| DomainError::Unexpected(e.to_string()))?;
match row {
Some(u) => Ok(User {
id: u.id,
name: u.name,
email: u.email,
}),
None => Err(DomainError::NotFound),
}
}
async fn list(&self) -> Result<Vec<User>, DomainError> {
let rows = sqlx::query_as!(UserRow, r#"SELECT id, name, email FROM users"#)
.fetch_all(&self.pool)
.await
.map_err(|e| DomainError::Unexpected(e.to_string()))?;
Ok(rows
.into_iter()
.map(|u| User {
id: u.id,
name: u.name,
email: u.email,
})
.collect())
}
}
src/infrastructure/http/mod.rs
pub mod handlers;
pub mod routes;
src/infrastructure/http/handlers.rs
use actix_web::{web, HttpResponse, ResponseError};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::application::user_service::UserService;
use crate::domain::error::DomainError;
use crate::domain::ports::UserRepository;
use crate::domain::user::User;
#[derive(Debug, Deserialize)]
pub struct CreateUserRequest {
pub name: String,
pub email: String,
}
#[derive(Debug, Serialize)]
pub struct UserResponse {
pub id: Uuid,
pub name: String,
pub email: String,
}
impl From<User> for UserResponse {
fn from(u: User) -> Self {
UserResponse {
id: u.id,
name: u.name,
email: u.email,
}
}
}
// Map domain errors to HTTP responses.
impl ResponseError for DomainError {
fn error_response(&self) -> HttpResponse {
match self {
DomainError::NotFound => HttpResponse::NotFound().body("Not found"),
DomainError::AlreadyExists => HttpResponse::Conflict().body("Already exists"),
DomainError::Validation(msg) => HttpResponse::BadRequest().body(msg.to_string()),
DomainError::Unexpected(msg) => HttpResponse::InternalServerError().body(msg.to_string()),
}
}
}
// Handlers
pub async fn create_user<R: UserRepository>(
service: web::Data<UserService<R>>,
payload: web::Json<CreateUserRequest>,
) -> Result<HttpResponse, DomainError> {
let user = service
.create_user(payload.name.clone(), payload.email.clone())
.await?;
Ok(HttpResponse::Created().json(UserResponse::from(user)))
}
pub async fn get_user<R: UserRepository>(
service: web::Data<UserService<R>>,
path: web::Path<Uuid>,
) -> Result<HttpResponse, DomainError> {
let user = service.get_user(path.into_inner()).await?;
Ok(HttpResponse::Ok().json(UserResponse::from(user)))
}
pub async fn list_users<R: UserRepository>(
service: web::Data<UserService<R>>,
) -> Result<HttpResponse, DomainError> {
let users = service.list_users().await?;
let resp: Vec<UserResponse> = users.into_iter().map(UserResponse::from).collect();
Ok(HttpResponse::Ok().json(resp))
}
src/infrastructure/http/routes.rs
use actix_web::web;
use crate::domain::ports::UserRepository;
use super::handlers::{create_user, get_user, list_users};
pub fn configure<R: UserRepository + 'static>(cfg: &mut web::ServiceConfig) {
cfg.service(
web::scope("/users")
.route("", web::post().to(create_user::<R>))
.route("", web::get().to(list_users::<R>))
.route("/{id}", web::get().to(get_user::<R>)),
);
}
src/main.rs
mod domain;
mod application;
mod infrastructure;
use actix_web::{App, HttpServer, web};
use sqlx::postgres::PgPoolOptions;
use crate::application::user_service::UserService;
use crate::infrastructure::db::SqlxUserRepository;
use crate::infrastructure::http::routes;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
dotenvy::dotenv().ok();
env_logger::init();
let database_url =
std::env::var("DATABASE_URL").expect("DATABASE_URL must be set, e.g. postgres://...");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.expect("cannot connect to database");
// Adapters (DB) implement domain port.
let user_repo = SqlxUserRepository::new(pool.clone());
// Application service depends on the domain port, not on actix or sqlx.
let user_service = UserService::new(user_repo);
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(user_service.clone()))
.configure(routes::configure::<SqlxUserRepository>)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
Notes
-
Hexagonal:
- Domain: Entities (
User), errors, and ports (UserRepository trait).
- Application: Use cases (
UserService) depend on ports, not on HTTP or SQL.
- Infrastructure: Adapters (Actix handlers and SQLx repository) implement ports and translate the outside world into the domain.
-
SQLx compile‑time checks:
-
Extending: Add more ports (e.g., message bus, cache), adapters, or use cases without touching HTTP or database code.