Absolutely! Below is a minimal but complete example of a blog CMS in Rust using the axum web framework and PostgreSQL via sqlx. This example includes:
- A front page (
/) listing blog posts with title and summary, paginated.
- A post page (
/post/:id) showing the full content.
- Database migrations for the
posts table.
- Templating with askama for HTML rendering.
Assumptions:
- You have a running PostgreSQL instance.
- You have Rust and Cargo installed.
- You are familiar with running migrations and setting up environment variables.
1. Cargo.toml
[package]
name = "blog_cms"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.7", features = ["runtime-tokio", "postgres", "macros", "uuid"] }
serde = { version = "1", features = ["derive"] }
askama = "0.12"
dotenvy = "0.15"
uuid = { version = "1", features = ["v4", "serde"] }
2. Database Migration
Create a migration file (e.g., migrations/20240101_create_posts.sql):
CREATE TABLE posts (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
summary TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
3. main.rs
use askama::Template;
use axum::{
extract::{Path, Query, State},
response::{Html, IntoResponse},
routing::get,
Router,
};
use serde::Deserialize;
use sqlx::{postgres::PgPoolOptions, PgPool};
use std::net::SocketAddr;
use uuid::Uuid;
#[derive(sqlx::FromRow, Debug, Clone)]
struct Post {
id: Uuid,
title: String,
summary: String,
content: String,
created_at: chrono::NaiveDateTime,
}
#[derive(Template)]
#[template(path = "index.html")]
struct IndexTemplate {
posts: Vec<Post>,
page: usize,
total_pages: usize,
}
#[derive(Template)]
#[template(path = "post.html")]
struct PostTemplate {
post: Post,
}
#[derive(Deserialize)]
struct Pagination {
page: Option<usize>,
}
async fn list_posts(
State(pool): State<PgPool>,
Query(pagination): Query<Pagination>,
) -> impl IntoResponse {
let page = pagination.page.unwrap_or(1);
let per_page = 5;
let offset = (page - 1) * per_page;
let posts: Vec<Post> = sqlx::query_as::<_, Post>(
"SELECT * FROM posts ORDER BY created_at DESC LIMIT $1 OFFSET $2",
)
.bind(per_page as i64)
.bind(offset as i64)
.fetch_all(&pool)
.await
.unwrap_or_default();
let total: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM posts")
.fetch_one(&pool)
.await
.unwrap_or((0,));
let total_pages = ((total.0 as f64) / (per_page as f64)).ceil() as usize;
let template = IndexTemplate {
posts,
page,
total_pages,
};
Html(template.render().unwrap())
}
async fn show_post(
State(pool): State<PgPool>,
Path(id): Path<Uuid>,
) -> impl IntoResponse {
let post = sqlx::query_as::<_, Post>("SELECT * FROM posts WHERE id = $1")
.bind(id)
.fetch_one(&pool)
.await
.ok();
if let Some(post) = post {
let template = PostTemplate { post };
Html(template.render().unwrap()).into_response()
} else {
(axum::http::StatusCode::NOT_FOUND, "Post not found").into_response()
}
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
let database_url = std::env::var("DATABASE_URL")
.expect("DATABASE_URL must be set in .env");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await?;
let app = Router::new()
.route("/", get(list_posts))
.route("/post/:id", get(show_post))
.with_state(pool);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("Listening on http://{}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await?;
Ok(())
}
4. Templates
Create a templates/ directory in your project root.
templates/index.html
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>Blog Posts</h1>
<ul>
{% for post in posts %}
<li>
<h2><a href="/post/{{ post.id }}">{{ post.title }}</a></h2>
<p>{{ post.summary }}</p>
<small>Posted at {{ post.created_at }}</small>
</li>
{% endfor %}
</ul>
<div>
{% if page > 1 %}
<a href="/?page={{ page - 1 }}">Previous</a>
{% endif %}
Page {{ page }} of {{ total_pages }}
{% if page < total_pages %}
<a href="/?page={{ page + 1 }}">Next</a>
{% endif %}
</div>
</body>
</html>
templates/post.html
<!DOCTYPE html>
<html>
<head>
<title>{{ post.title }}</title>
</head>
<body>
<h1>{{ post.title }}</h1>
<p><small>Posted at {{ post.created_at }}</small></p>
<div>
{{ post.content | safe }}
</div>
<p><a href="/">Back to list</a></p>
</body>
</html>
5. .env file
DATABASE_URL=postgres://username:password@localhost/blog_cms
6. Running
- Run migrations (e.g., with sqlx-cli):
sqlx migrate run
- Start the server:
cargo run
- Visit http://localhost:3000
7. Inserting Posts
You can insert posts manually for now:
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.');
8. Notes
- This is a minimal example. For production, add error handling, authentication, admin panel, etc.
- You can use axum-extra for more features.
- For markdown support, consider using pulldown-cmark.
Let me know if you want to add post creation, editing, or authentication!