write a blog CMS written in rust language. For now, it should at least have a front page…
- User
write a blog CMS written in rust language. For now, it should at least have a front page showing lists of blog posts with each having a title and summary of the contents, pagination, and there is also a post page where we can see the full content of the post.
I want it to be written in axum framework, uses postgresql database
- Assistant
Sure! Below is a minimal but functional blog CMS written in Rust using the Axum web framework and PostgreSQL as the database. This CMS includes:
- A front page that lists blog posts with title and summary.
- Pagination support.
- A post page that shows the full content of a blog post.
🦀 Tech Stack:
- Rust
- Axum (web framework)
- SQLx (async PostgreSQL driver)
- PostgreSQL
- Tera (template engine)
📁 Project Structure:
. ├── Cargo.toml ├── .env ├── src │ ├── main.rs │ ├── db.rs │ ├── handlers.rs │ ├── models.rs │ └── templates/ │ ├── index.html │ └── post.html
Step-by-step Implementation
- 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", "chrono"] } serde = { version = "1", features = ["derive"] } serde_json = "1" tera = "1.19" dotenvy = "0.15" uuid = { version = "1", features = ["v4"] } chrono = { version = "0.4", features = ["serde"] } tower = "0.4" tower-http = { version = "0.4", features = ["trace"] } tracing = "0.1" tracing-subscriber = "0.3"
- .env
DATABASE_URL=postgres://username:password@localhost/blog_cms
- Database Schema
Run this SQL to create the posts table:
CREATE TABLE posts ( id UUID PRIMARY KEY, title TEXT NOT NULL, summary TEXT NOT NULL, content TEXT NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT NOW() );
- src/db.rs
use sqlx::{PgPool, postgres::PgPoolOptions}; use std::env;
pub async fn init_db() -> PgPool { let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set"); PgPoolOptions::new() .max_connections(5) .connect(&database_url) .await .expect("Failed to connect to database") }
- src/models.rs
use serde::{Deserialize, Serialize}; use sqlx::FromRow; use uuid::Uuid; use chrono::{DateTime, Utc};
#[derive(Debug, Serialize, FromRow)] pub struct Post { pub id: Uuid, pub title: String, pub summary: String, pub content: String, pub created_at: DateTime, }
- src/handlers.rs
use axum::{ extract::{Path, Query, State}, response::Html, }; use std::collections::HashMap; use tera::Tera; use uuid::Uuid;
use crate::{models::Post, AppState};
#[derive(Debug, Deserialize)] pub struct Pagination { pub page: Option, }
pub async fn list_posts( State(state): State, Query(pagination): Query, ) -> Html { let page = pagination.page.unwrap_or(1); let per_page = 5; let offset = (page - 1) * per_page;
let posts = 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(&state.db) .await .unwrap(); let mut context = tera::Context::new(); context.insert("posts", &posts); context.insert("page", &page); let rendered = state .templates .render("index.html", &context) .unwrap(); Html(rendered)}
pub async fn show_post( State(state): State, Path(id): Path, ) -> Html { let post = sqlx::query_as::<_, Post>("SELECT * FROM posts WHERE id = $1") .bind(id) .fetch_one(&state.db) .await .unwrap();
let mut context = tera::Context::new(); context.insert("post", &post); let rendered = state .templates .render("post.html", &context) .unwrap(); Html(rendered)}
- src/main.rs
mod db; mod handlers; mod models;
use axum::{ routing::get, Router, }; use std::net::SocketAddr; use tera::Tera; use dotenvy::dotenv; use std::sync::Arc; use sqlx::PgPool;
#[derive(Clone)] pub struct AppState { pub db: PgPool, pub templates: Arc, }
#[tokio::main] async fn main() { dotenv().ok(); tracing_subscriber::fmt::init();
let db = db::init_db().await; let templates = Tera::new("src/templates/**/*").unwrap(); let state = AppState { db, templates: Arc::new(templates), }; let app = Router::new() .route("/", get(handlers::list_posts)) .route("/post/:id", get(handlers::show_post)) .with_state(state); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("Listening on http://{}", addr); axum::Server::bind(&addr) .serve(app.into_make_service()) .await .unwrap();}
- src/templates/index.html
<div> <a href="/?page={{ page | minus(1) }}">Previous</a> | <a href="/?page={{ page | plus(1) }}">Next</a> </div>- src/templates/post.html
🧪 Running the App
- Set up your PostgreSQL database and run the schema.
- Add some test data.
- Run the app:
cargo run
Visit http://localhost:3000 to see the blog.
✅ Next Steps
- Add admin panel for creating/editing posts.
- Add markdown support.
- Add authentication.
- Add tags/categories.
Let me know if you want to expand this CMS further!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.