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
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating a simple blog CMS in Rust using the Axum framework and PostgreSQL involves several steps. Below is a basic implementation that includes a front page displaying a list of blog posts with titles and summaries, pagination, and a post page for viewing the full content of each post.
Prerequisites
Rust: Make sure you have Rust installed. You can install it from rustup.rs.
PostgreSQL: Ensure you have PostgreSQL installed and running.
Dependencies: We'll use axum, tokio, sqlx, and serde for our application.
Step 1: Create a New Rust Project
bash
cargo new blog_cms
cd blog_cms
Step 2: Update Cargo.toml
Add the necessary dependencies to your Cargo.toml file:
toml
[dependencies]
axum = "0.6"
tokio = { version = "1", features = ["full"] }
sqlx = { version = "0.5", features = ["runtime-tokio-rustls", "postgres"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1.0"
tower = "0.4"
dotenv = "0.15"
Step 3: Set Up the Database
Create a PostgreSQL database and a table for blog posts. You can use the following SQL commands:
sql
CREATE DATABASE blog_cms;
\c blog_cms;
CREATE TABLE posts (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
summary TEXT NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Step 4: Create the Application
Create a new file src/main.rs and add the following code:
rust
use axum::{
extract::{Extension, Query},
response::Html,
routing::{get, Router},
};
use sqlx::postgres::PgPoolOptions;
use serde::Deserialize;
use std::net::SocketAddr;
use dotenv::dotenv;
use std::env;
#[derive(Debug, sqlx::FromRow)]
struct Post {
id: i32,
title: String,
summary: String,
content: String,
created_at: chrono::NaiveDateTime,
}
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
}
async fn list_posts(
Query(pagination): Query<Pagination>,
Extension(pool): Extension<sqlx::PgPool>,
) -> Html<String> {
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,
r#"
SELECT id, title, summary, content, created_at
FROM posts
ORDER BY created_at DESC
LIMIT $1 OFFSET $2
"#,
per_page as i64,
offset as i64
)
.fetch_all(&pool)
.await
.unwrap();
let mut html = String::new();
html.push_str("<h1>Blog Posts</h1><ul>");
for post in posts {
html.push_str(&format!(
"<li><a href=\"/post/{}\">{}</a>: {}</li>",
post.id, post.title, post.summary
));
}
html.push_str("</ul>");
// Pagination links
html.push_str("<div>");
if page > 1 {
html.push_str(&format!("<a href=\"/?page={}\">Previous</a> ", page - 1));
}
html.push_str(&format!("<a href=\"/?page={}\">Next</a>", page + 1));
html.push_str("</div>");
Html(html)
}
async fn get_post(
Extension(pool): Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<i32>,
) -> Html<String> {
let post: Post = sqlx::query_as!(
Post,
r#"
SELECT id, title, summary, content, created_at
FROM posts
WHERE id = $1
"#,
id
)
.fetch_one(&pool)
.await
.unwrap();
let html = format!(
"<h1>{}</h1><p>{}</p><p>{}</p>",
post.title, post.created_at, post.content
);
Html(html)
}
#[tokio::main]
async fn main() {
dotenv().ok();
let database_url = env::var("DATABASE_URL").expect("DATABASE_URL must be set");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await
.unwrap();
let app = Router::new()
.route("/", get(list_posts))
.route("/post/:id", get(get_post))
.layer(Extension(pool));
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
println!("Listening on {}", addr);
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
Step 5: Set Up Environment Variables
Create a .env file in the root of your project and add your PostgreSQL connection string:
Replace username and password with your PostgreSQL credentials.
Step 6: Run the Application
Make sure your PostgreSQL server is running, and then run your application:
bash
cargo run
Step 7: Test the Application
Open your web browser and navigate to http://localhost:3000. You should see a list of blog posts. You can click on the titles to view the full content of each post.
Conclusion
This is a basic implementation of a blog CMS using Rust, Axum, and PostgreSQL. You can expand this application by adding features like creating, editing, and deleting posts, user authentication, and more. Happy coding!