Creating a blog CMS in Rust using the Axum framework and PostgreSQL is a great project to learn about web development in Rust. Below is a basic implementation of the requested functionality. This example will include:
- A front page that lists blog posts with titles, summaries, and pagination.
- A post page to display the full content of a blog post.
- Integration with PostgreSQL for storing and retrieving blog posts.
Prerequisites
Before we start, ensure you have the following installed:
- Rust (with
cargo)
- PostgreSQL
Project Setup
-
Create a new Rust project:
cargo new blog_cms
cd blog_cms
-
Add the required dependencies to your Cargo.toml:
[dependencies]
axum = "0.6"
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.7", features = ["runtime-tokio-native-tls", "postgres"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
tower = "0.4"
tower-http = { version = "0.4", features = ["trace"] }
dotenvy = "0.15"
-
Set up a .env file for database configuration:
DATABASE_URL=postgres://username:password@localhost/blog_cms
Replace username and password with your PostgreSQL credentials.
-
Create the database and a posts table:
CREATE DATABASE blog_cms;
\c blog_cms
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title TEXT NOT NULL,
summary TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT NOW()
);
Code Implementation
Here is the complete implementation of the blog CMS:
src/main.rs
use axum::{
extract::{Path, Query, State},
http::StatusCode,
response::{Html, IntoResponse},
routing::get,
Json, Router,
};
use serde::{Deserialize, Serialize};
use sqlx::{postgres::PgPoolOptions, Pool, Postgres};
use std::sync::Arc;
#[tokio::main]
async fn main() {
// Load environment variables
dotenvy::dotenv().ok();
// Initialize the database connection pool
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.expect("Failed to connect to the database");
// Create the application state
let app_state = AppState {
db_pool: Arc::new(pool),
};
// Build the application router
let app = Router::new()
.route("/", get(list_posts))
.route("/post/:id", get(view_post))
.with_state(app_state);
// Run the server
let addr = "127.0.0.1:3000".parse().unwrap();
println!("Server running at http://{}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
// Application state
#[derive(Clone)]
struct AppState {
db_pool: Arc<Pool<Postgres>>,
}
// Blog post model
#[derive(Serialize)]
struct Post {
id: i32,
title: String,
summary: String,
content: String,
created_at: String,
}
// Query parameters for pagination
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
per_page: Option<u32>,
}
// Handler to list blog posts with pagination
async fn list_posts(
State(state): State<AppState>,
Query(pagination): Query<Pagination>,
) -> impl IntoResponse {
let page = pagination.page.unwrap_or(1);
let per_page = pagination.per_page.unwrap_or(5);
let offset = (page - 1) * per_page;
let posts = sqlx::query_as!(
Post,
r#"
SELECT id, title, summary, content, created_at::TEXT
FROM posts
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
"#,
per_page as i64,
offset as i64
)
.fetch_all(&*state.db_pool)
.await
.unwrap_or_else(|_| vec![]);
let html = posts
.into_iter()
.map(|post| {
format!(
r#"<h2><a href="/post/{}">{}</a></h2><p>{}</p>"#,
post.id, post.title, post.summary
)
})
.collect::<Vec<_>>()
.join("<hr>");
Html(format!(
r#"
<html>
<body>
<h1>Blog Posts</h1>
{}
<div>
<a href="/?page={}">Previous</a> | <a href="/?page={}">Next</a>
</div>
</body>
</html>
"#,
html,
if page > 1 { page - 1 } else { 1 },
page + 1
))
}
// Handler to view a single blog post
async fn view_post(State(state): State<AppState>, Path(id): Path<i32>) -> impl IntoResponse {
let post = sqlx::query_as!(
Post,
r#"
SELECT id, title, summary, content, created_at::TEXT
FROM posts
WHERE id = $1
"#,
id
)
.fetch_one(&*state.db_pool)
.await;
match post {
Ok(post) => Html(format!(
r#"
<html>
<body>
<h1>{}</h1>
<p><i>{}</i></p>
<div>{}</div>
<a href="/">Back to home</a>
</body>
</html>
"#,
post.title, post.created_at, post.content
))
.into_response(),
Err(_) => (StatusCode::NOT_FOUND, "Post not found").into_response(),
}
}
Explanation
-
Database Connection:
- The
sqlx library is used to connect to the PostgreSQL database.
- The
AppState struct holds the database connection pool, which is shared across handlers.
-
Pagination:
- The
list_posts handler accepts query parameters (page and per_page) for pagination.
- SQL's
LIMIT and OFFSET are used to fetch the appropriate posts.
-
Post Viewing:
- The
view_post handler fetches a single post by its ID and displays its full content.
-
HTML Rendering:
- Basic HTML is used to render the front page and post page.
Running the Application
-
Start the server:
cargo run
-
Open your browser and navigate to http://127.0.0.1:3000.
Adding Blog Posts
You can manually insert blog posts into the database for testing:
INSERT INTO posts (title, summary, content) VALUES
('First Post', 'This is the summary of the first post', 'This is the full content of the first post.'),
('Second Post', 'This is the summary of the second post', 'This is the full content of the second post.');
This implementation provides a basic blog CMS. You can extend it by adding features like user authentication, an admin panel for creating/editing posts, and more!