I'm zeroing in on the fundamental application structure needed for a Rust web service. It's becoming clearer: we require a setup for actix-web and Diesel. My current focus is identifying the essential components: data models, routes, database connection, and error handling, all with best practices in mind.
Structuring the Foundation
I've got a firm grasp on the project's skeleton. I'm focusing on organizing the core elements: src layout, dependencies, and database integration. The plan is clear: actix-web, Diesel, and supporting crates are the tools. Now, it's about connecting the dots to establish a solid foundation for the data models, routes, database, and all the rest. I'm moving step-by-step, building a clear path from setup to working server, including migrations.
Pinpointing Dependencies and Structure
I've meticulously outlined the critical dependencies and directory structure. I'm focusing on the Cargo.toml file, confirming the need for actix-web, diesel with postgres and r2d2 features, serde and json, dotenvy, and env_logger. The directory structure is also taking shape: src/main.rs, schema.rs, models.rs, db.rs, and a handlers.rs for simple handlers. I've also noted database setup with the standard DATABASE_URL in .env. The database module is designed to include type aliases and a function for initializing the connection pool. Now, I'll define a dummy entity to generate the schema.rs with Diesel.
Developing Module Structures
I'm structuring the code more efficiently with a clear split into modules. The plan is to create user models (Queryable, Insertable, Serialize/Deserialize), along with handlers to create and get users using the database pool. Critical, now, is the explicit use of web::block in the handlers for synchronous Diesel operations. The main.rs file will focus on .env loading, logger init, pool creation, and server setup with routing. This refined structure is starting to feel much more robust.
Confirming the Structure
The project skeleton is in place. I'm focusing on clarifying how it will run and making sure the explanations are concise and targeted. Specifically, I am writing out the explanations for why web::block is used and documenting the project structure, including the necessary setup for Diesel, to make the structure clear. I also aim to make the documentation clear. The plan includes verifying the setup.
Here is a robust boilerplate for a REST API using Actix-web (v4) and Diesel (v2) with PostgreSQL.
This setup separates concerns into modules (handlers, models, database configuration) and handles the integration between Actix's asynchronous nature and Diesel's synchronous blocking operations.
Here we define structs for reading from the DB (Queryable) and writing to the DB (Insertable).
rust
use diesel::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::schema::users;
#[derive(Queryable, Serialize)]
pub struct User {
pub id: Uuid,
pub username: String,
pub email: String,
}
#[derive(Insertable, Deserialize)]
#[diesel(table_name = users)]
pub struct NewUser {
pub username: String,
pub email: String,
}
src/db.rs
We set up a connection pool using r2d2. Since creating a connection for every request is slow, pooling is essential.
rust
use diesel::pg::PgConnection;
use diesel::r2d2::ConnectionManager;
use std::env;
pub type DbPool = diesel::r2d2::Pool<ConnectionManager<PgConnection>>;
pub fn establish_connection() -> DbPool {
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let manager = ConnectionManager::<PgConnection>::new(database_url);
diesel::r2d2::Pool::builder()
.build(manager)
.expect("Failed to create DB pool")
}
src/handlers.rs
This contains the API logic.
Crucial: Because Diesel is synchronous (blocking) and Actix is asynchronous, we must wrap DB calls in web::block. This offloads the query to a thread pool so the web server doesn't freeze.
rust
use actix_web::{web, HttpResponse, Responder};
use diesel::prelude::*;
use uuid::Uuid;
use crate::db::DbPool;
use crate::models::{NewUser, User};
use crate::schema::users::dsl::*;
// POST /users
pub async fn create_user(
pool: web::Data<DbPool>,
new_user: web::Json<NewUser>,
) -> impl Responder {
let user_id = Uuid::new_v4();
let user = User {
id: user_id,
username: new_user.username.clone(),
email: new_user.email.clone(),
};
// web::block allows sync code to run in async context
let result = web::block(move || {
let mut conn = pool.get().expect("couldn't get db connection from pool");
diesel::insert_into(users)
.values(&user)
.execute(&mut conn)
})
.await;
match result {
Ok(_) => HttpResponse::Created().json(user),
Err(_) => HttpResponse::InternalServerError().finish(),
}
}
// GET /users/{id}
pub async fn get_user(
pool: web::Data<DbPool>,
path_id: web::Path<Uuid>,
) -> impl Responder {
let user_uid = path_id.into_inner();
let result = web::block(move || {
let mut conn = pool.get().expect("couldn't get db connection from pool");
users
.filter(id.eq(user_uid))
.first::<User>(&mut conn)
})
.await;
match result {
Ok(Ok(user)) => HttpResponse::Ok().json(user),
Ok(Err(_)) => HttpResponse::NotFound().body("User not found"),
Err(_) => HttpResponse::InternalServerError().finish(),
}
}
src/main.rs
Wiring it all together.
rust
mod db;
mod handlers;
mod models;
mod schema;
use actix_web::{web, App, HttpServer};
use dotenvy::dotenv;
use std::env;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Load env vars
dotenv().ok();
env_logger::init();
// Create DB Pool
let pool = db::establish_connection();
let host = env::var("HOST").unwrap_or_else(|_| "127.0.0.1".to_string());
let port = env::var("PORT").unwrap_or_else(|_| "8080".to_string());
let addr = format!("{}:{}", host, port);
println!("Server running at http://{}", addr);
HttpServer::new(move || {
App::new()
// Pass the pool to handlers
.app_data(web::Data::new(pool.clone()))
// Register routes
.service(
web::scope("/api")
.route("/users", web::post().to(handlers::create_user))
.route("/users/{id}", web::get().to(handlers::get_user)),
)
})
.bind(addr)?
.run()
.await
}
6. How to Run
Ensure Postgres is running and DATABASE_URL is correct in .env.