Creating a Rust web service boilerplate
The user needs a boilerplate for a Rust web service utilizing Actix-web and Diesel. I should provide a concise yet informative structure that includes an overview and a sample project layout with files such as Cargo.toml, main.rs, and configuration files.
Actix-web should be version 4, Diesel version 2, and typically I'd use Postgres for the database with Diesel features like postgres and r2d2. I’ll also create a minimal example with a health check endpoint and user CRUD operations. I'll check the crate versions to ensure they compile correctly.Building Diesel and Actix-web setup
I'll define the diesel package with the version 2 and necessary features like postgres, r2d2, and chrono. I’ll also include dotenvy for environment variable management and specify the uuid package.
It’s crucial to align with the diesel_migrations crate using embedded migrations while simplifying file names. The user wants a boilerplate, so I should provide minimal instructions on creating the project and setting up Diesel without excessive detail.
I'll structure the output with sections for project structure, Cargo.toml contents, .env, schema, migrations, database logic, models, routes, configuration, and main file.Ensuring Diesel migration accuracy
I need to make sure I accurately implement Diesel 2 migrations. The new macro usage involves importing embed_migrations, EmbeddedMigrations, and MigrationHarness. I’ll define MIGRATIONS with the embedded migrations.
For running migrations, I could either take a connection from the pool or use a plain PgConnection. Using pooled_connection.run_pending_migrations(MIGRATIONS)? is an option, but I need to be careful with the &mut conn deref issue. A simpler approach could be to run migrations with a standard connection and then build the pool afterwards. This will ensure everything is set up correctly before pooling connections.Setting up database connection and blocking tasks
For establishing a PostgreSQL connection, I can use let mut conn = PgConnection::establish(&database_url)?; run_migrations(&mut conn)?; and then create a connection pool. Since both Actix-web and Diesel operate synchronously, I need to use web::block to handle blocking database operations effectively.
In the boilerplate, I’ll include a simple GET handler for retrieving users using web::Data<DbPool>. However, to keep it concise, I might demonstrate just a health check and a user creation/listing function. I also need to remind the user to enable Diesel CLI with cargo install diesel_cli --no-default-features --features postgres. I'll make it clear that this is a template that may need adjustments, and I’m aware that crate versions are approximate as of late 2024.Finalizing Rust web service boilerplate
I need to manage r2d2 connections carefully. To get a connection from the pool, I’ll use let mut conn = pool.get().map_err(|e| e.to_string())?;. In the closure for web::block, it should return Result<Vec<User>, DbError>, where I can define DbError as Box<dyn std::error::Error + Send + Sync + 'static> for improved error handling.
For the user creation endpoint, I’ll implement it in the create_user function, using web::block to execute the database operation while handling potential errors appropriately.
I'll set up logging and modules in the main function and note that schema.rs is auto-generated, encouraging users to run migrations properly. Lastly, I’ll provide a minimal description and outline setup steps to ensure clarity. Below is a small, opinionated boilerplate for an Actix‑web + Diesel (PostgreSQL) service with:
- Env‑based config
- Connection pool (r2d2)
- Embedded migrations
- Health check
- Example
User model + simple endpoints
You can copy this into a new project and adjust as needed.
1. Project layout
my-service/
├─ Cargo.toml
├─ .env
├─ migrations/
│ └─ 00000000000000_create_users/
│ ├─ up.sql
│ └─ down.sql
└─ src/
├─ main.rs
├─ config.rs
├─ db.rs
├─ models.rs
├─ schema.rs
└─ routes/
├─ mod.rs
├─ health.rs
└─ users.rs
2. Cargo.toml
[package]
name = "my-service"
version = "0.1.0"
edition = "2021"
[dependencies]
actix-web = "4"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
dotenvy = "0.15"
env_logger = "0.11"
log = "0.4"
chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["v4", "serde"] }
diesel = { version = "2", features = ["postgres", "r2d2", "chrono", "uuid"] }
diesel_migrations = "2"
3. .env
DATABASE_URL=postgres://postgres:password@localhost/my_service
SERVER_HOST=127.0.0.1
SERVER_PORT=8080
RUST_LOG=info,my_service=debug
4. Migrations
migrations/00000000000000_create_users/up.sql
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
email VARCHAR NOT NULL UNIQUE,
name VARCHAR NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
migrations/00000000000000_create_users/down.sql
DROP TABLE IF EXISTS users;
5. src/config.rs
use std::env;
#[derive(Clone)]
pub struct Settings {
pub database_url: String,
pub host: String,
pub port: u16,
}
impl Settings {
pub fn from_env() -> Self {
// Load .env if present
dotenvy::dotenv().ok();
let database_url = env::var("DATABASE_URL")
.expect("DATABASE_URL must be set");
let host = env::var("SERVER_HOST")
.unwrap_or_else(|_| "127.0.0.1".into());
let port = env::var("SERVER_PORT")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(8080);
Settings {
database_url,
host,
port,
}
}
}
6. src/db.rs
use diesel::pg::PgConnection;
use diesel::r2d2::{self, ConnectionManager};
use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness};
use crate::config::Settings;
pub type DbPool = r2d2::Pool<ConnectionManager<PgConnection>>;
pub type DbError = Box<dyn std::error::Error + Send + Sync + 'static>;
pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations");
pub fn init_pool(settings: &Settings) -> DbPool {
// Run migrations once before creating the pool
{
let mut conn = PgConnection::establish(&settings.database_url)
.unwrap_or_else(|e| panic!("Error connecting to {}: {}", settings.database_url, e));
run_migrations(&mut conn);
}
let manager = ConnectionManager::<PgConnection>::new(settings.database_url.clone());
r2d2::Pool::builder()
.build(manager)
.expect("Failed to create DB connection pool")
}
fn run_migrations(conn: &mut PgConnection) {
conn.run_pending_migrations(MIGRATIONS)
.expect("Failed to run database migrations");
}
7. src/schema.rs
In a real project, you’d generate this with diesel print-schema > src/schema.rs. For the example table above:
// @generated automatically by Diesel CLI.
diesel::table! {
users (id) {
id -> Uuid,
email -> Varchar,
name -> Varchar,
created_at -> Timestamptz,
}
}
8. src/models.rs
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use diesel::prelude::*;
use crate::schema::users;
#[derive(Debug, Serialize, Queryable, Identifiable)]
#[diesel(table_name = users)]
pub struct User {
pub id: Uuid,
pub email: String,
pub name: String,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Deserialize, Insertable)]
#[diesel(table_name = users)]
pub struct NewUser {
pub email: String,
pub name: String,
}
9. src/routes/mod.rs
pub mod health;
pub mod users;
10. src/routes/health.rs
use actix_web::{get, HttpResponse, Responder};
use serde_json::json;
#[get("/health")]
pub async fn health() -> impl Responder {
HttpResponse::Ok().json(json!({ "status": "ok" }))
}
11. src/routes/users.rs
use actix_web::{get, post, web, HttpResponse, Responder};
use diesel::prelude::*;
use crate::db::{DbError, DbPool};
use crate::models::{NewUser, User};
use crate::schema::users::dsl::*;
#[get("/users")]
pub async fn list_users(pool: web::Data<DbPool>) -> actix_web::Result<impl Responder> {
let pool = pool.clone();
let result = web::block(move || {
let mut conn = pool.get()?; // r2d2::Error -> DbError
let items = users
.order(created_at.desc())
.load::<User>(&mut conn)?; // diesel::Error -> DbError
Ok::<_, DbError>(items)
})
.await
.map_err(actix_web::error::ErrorInternalServerError)??;
Ok(HttpResponse::Ok().json(result))
}
#[post("/users")]
pub async fn create_user(
pool: web::Data<DbPool>,
payload: web::Json<NewUser>,
) -> actix_web::Result<impl Responder> {
let new_user = payload.into_inner();
let pool = pool.clone();
let created = web::block(move || {
let mut conn = pool.get()?;
diesel::insert_into(users)
.values(&new_user)
.get_result::<User>(&mut conn)
.map_err(|e| -> DbError { Box::new(e) })
})
.await
.map_err(actix_web::error::ErrorInternalServerError)??;
Ok(HttpResponse::Created().json(created))
}
12. src/main.rs
mod config;
mod db;
mod models;
mod routes;
mod schema;
use actix_web::{middleware::Logger, web, App, HttpServer};
use crate::config::Settings;
use crate::db::init_pool;
use crate::routes::health::health;
use crate::routes::users::{create_user, list_users};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
env_logger::init();
let settings = Settings::from_env();
let pool = init_pool(&settings);
let bind_addr = format!("{}:{}", settings.host, settings.port);
println!("Starting server on http://{}", bind_addr);
HttpServer::new(move || {
App::new()
.wrap(Logger::default())
.app_data(web::Data::new(pool.clone()))
.service(health)
.service(list_users)
.service(create_user)
})
.bind(bind_addr)?
.run()
.await
}
13. Setup / run steps
From an empty directory:
# 1. Create the project
cargo new my-service
cd my-service
# 2. Replace Cargo.toml and add the src/ files and .env as above
# 3. Install Diesel CLI (Postgres)
cargo install diesel_cli --no-default-features --features postgres
# 4. Initialize Diesel (creates migrations folder, etc.)
diesel setup
# 5. Add the `create_users` migration as shown and run it
diesel migration run
# 6. Run the server
cargo run
Then:
If you’d like, I can adapt this boilerplate for another DB (e.g., SQLite) or add auth/more structured error handling.