This commit is contained in:
2026-03-25 10:58:10 +01:00
commit 07c4c04eb7
23 changed files with 7365 additions and 0 deletions

8
.env.example Normal file
View File

@@ -0,0 +1,8 @@
# Backend Configuration
PORT=3000
ADMIN_TOKEN=your_secure_random_token_here
DATA_DIR=/app/data
# Frontend Configuration
# URL of the backend API accessible from the frontend container
PUBLIC_API_URL=http://backend:3000

34
.gitignore vendored Normal file
View File

@@ -0,0 +1,34 @@
# IDEs
.vscode/
.idea/
*.swp
*.swo
.DS_Store
Thumbs.db
# Environment
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Backend (Rust)
backend/target/
backend/**/*.rs.bk
# Frontend (Node/Astro)
frontend/node_modules/
frontend/dist/
frontend/.astro/
frontend/npm-debug.log*
frontend/yarn-debug.log*
frontend/yarn-error.log*
frontend/.pnpm-debug.log*
# Data (Persistent storage)
# We might want to keep the directory structure but ignore the actual content
# data/posts/*
# data/uploads/*
# !data/posts/hello-world.md
# !data/posts/another-post.md

1
backend/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/target

1060
backend/Cargo.lock generated Normal file

File diff suppressed because it is too large Load Diff

16
backend/Cargo.toml Normal file
View File

@@ -0,0 +1,16 @@
[package]
name = "backend"
version = "0.1.0"
edition = "2024"
[dependencies]
axum = { version = "0.8.8", features = ["multipart", "macros"] }
chrono = { version = "0.4.44", features = ["serde"] }
dotenvy = "0.15.7"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
slug = "0.1.6"
tokio = { version = "1.50.0", features = ["full"] }
tower-http = { version = "0.6.8", features = ["cors", "fs"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }

14
backend/Dockerfile Normal file
View File

@@ -0,0 +1,14 @@
FROM rust:1.75-slim as builder
WORKDIR /usr/src/app
COPY . .
RUN cargo build --release
FROM debian:bookworm-slim
WORKDIR /app
COPY --from=builder /usr/src/app/target/release/backend /usr/local/bin/backend
EXPOSE 3000
CMD ["backend"]

177
backend/src/main.rs Normal file
View File

@@ -0,0 +1,177 @@
use axum::{
extract::{DefaultBodyLimit, Multipart, Path, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Json},
routing::{get, post},
Router,
};
use serde::{Deserialize, Serialize};
use std::{env, fs, path::PathBuf, sync::Arc};
use tower_http::{
cors::{Any, CorsLayer},
services::ServeDir,
};
use tracing::{error, info};
#[derive(Clone)]
struct AppState {
admin_token: String,
data_dir: PathBuf,
}
#[derive(Serialize)]
struct PostInfo {
slug: String,
}
#[derive(Serialize)]
struct PostDetail {
slug: String,
content: String,
}
#[derive(Serialize)]
struct ErrorResponse {
error: String,
}
#[derive(Serialize)]
struct UploadResponse {
url: String,
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
dotenvy::dotenv().ok();
let port = env::var("PORT").unwrap_or_else(|_| "3000".to_string());
let admin_token = env::var("ADMIN_TOKEN").unwrap_or_else(|_| "secret".to_string());
let data_dir_str = env::var("DATA_DIR").unwrap_or_else(|_| "../data".to_string());
let data_dir = PathBuf::from(data_dir_str);
// Ensure directories exist
let posts_dir = data_dir.join("posts");
let uploads_dir = data_dir.join("uploads");
fs::create_dir_all(&posts_dir).expect("Failed to create posts directory");
fs::create_dir_all(&uploads_dir).expect("Failed to create uploads directory");
let state = Arc::new(AppState {
admin_token,
data_dir,
});
let cors = CorsLayer::new()
.allow_origin(Any)
.allow_methods(Any)
.allow_headers(Any);
let app = Router::new()
.route("/api/posts", get(list_posts))
.route("/api/posts/:slug", get(get_post))
.route("/api/upload", post(upload_file))
.nest_service("/uploads", ServeDir::new(uploads_dir))
.layer(DefaultBodyLimit::max(10 * 1024 * 1024)) // 10MB limit
.layer(cors)
.with_state(state);
let addr = format!("0.0.0.0:{}", port);
info!("Starting server on {}", addr);
let listener = tokio::net::TcpListener::bind(&addr).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn list_posts(State(state): State<Arc<AppState>>) -> impl IntoResponse {
let posts_dir = state.data_dir.join("posts");
let mut posts = Vec::new();
if let Ok(entries) = fs::read_dir(posts_dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) == Some("md") {
if let Some(slug) = path.file_stem().and_then(|s| s.to_str()) {
posts.push(PostInfo {
slug: slug.to_string(),
});
}
}
}
}
Json(posts)
}
async fn get_post(
State(state): State<Arc<AppState>>,
Path(slug): Path<String>,
) -> Result<Json<PostDetail>, (StatusCode, Json<ErrorResponse>)> {
let file_path = state.data_dir.join("posts").join(format!("{}.md", slug));
// Security check to prevent directory traversal
if file_path.parent() != Some(&state.data_dir.join("posts")) {
return Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse { error: "Invalid slug".to_string() }),
));
}
match fs::read_to_string(&file_path) {
Ok(content) => Ok(Json(PostDetail { slug, content })),
Err(_) => Err((
StatusCode::NOT_FOUND,
Json(ErrorResponse { error: "Post not found".to_string() }),
)),
}
}
async fn upload_file(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
mut multipart: Multipart,
) -> Result<Json<UploadResponse>, (StatusCode, Json<ErrorResponse>)> {
// Basic Auth Check
let auth_header = headers.get("Authorization").and_then(|h| h.to_str().ok());
if auth_header != Some(&format!("Bearer {}", state.admin_token)) {
return Err((
StatusCode::UNAUTHORIZED,
Json(ErrorResponse { error: "Unauthorized".to_string() }),
));
}
while let Some(field) = multipart.next_field().await.map_err(|_| {
(StatusCode::BAD_REQUEST, Json(ErrorResponse { error: "Multipart error".to_string() }))
})? {
if let Some(file_name) = field.file_name() {
let file_name = slug::slugify(file_name);
let uploads_dir = state.data_dir.join("uploads");
let file_path = uploads_dir.join(&file_name);
// Simple conflict resolution
let final_path = if file_path.exists() {
let timestamp = chrono::Utc::now().timestamp();
uploads_dir.join(format!("{}_{}", timestamp, file_name))
} else {
file_path
};
let final_name = final_path.file_name().unwrap().to_str().unwrap().to_string();
let data = field.bytes().await.map_err(|_| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Read error".to_string() }))
})?;
fs::write(&final_path, &data).map_err(|_| {
(StatusCode::INTERNAL_SERVER_ERROR, Json(ErrorResponse { error: "Write error".to_string() }))
})?;
return Ok(Json(UploadResponse {
url: format!("/uploads/{}", final_name),
}));
}
}
Err((
StatusCode::BAD_REQUEST,
Json(ErrorResponse { error: "No file found".to_string() }),
))
}

View File

@@ -0,0 +1,19 @@
# My Second Blog Post
Adding some more content to test the layout and the glassy look!
### Markdown Testing
- **Bold text**
- *Italic text*
- [A link to GitHub](https://github.com)
> "The only way to do great work is to love what you do." - Steve Jobs
```rust
fn main() {
println!("Hello from Rust!");
}
```
Enjoy reading!

13
data/posts/hello-world.md Normal file
View File

@@ -0,0 +1,13 @@
# Welcome to Narlblog
This is my very first blog post! Built with a modern, glassy aesthetic and the beautiful Catppuccin color palette.
## Technical Stack
The blog is powered by:
- **Rust (Axum)**: Fast and reliable backend.
- **Astro**: Modern frontend framework for performance.
- **Tailwind CSS**: Glassy UI with Catppuccin theme.
- **Docker**: Simple containerized deployment.
Feel free to explore and add your own posts by creating `.md` files in the `data/posts` directory!

28
docker-compose.yml Normal file
View File

@@ -0,0 +1,28 @@
version: '3.8'
services:
backend:
build:
context: ./backend
dockerfile: Dockerfile
ports:
- "3000:3000"
volumes:
- ./data:/app/data
environment:
- PORT=3000
- ADMIN_TOKEN=${ADMIN_TOKEN:-default_insecure_token}
- DATA_DIR=/app/data
restart: unless-stopped
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
ports:
- "4321:4321"
environment:
- PUBLIC_API_URL=http://backend:3000
depends_on:
- backend
restart: unless-stopped

24
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# build output
dist/
# generated types
.astro/
# dependencies
node_modules/
# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# environment variables
.env
.env.production
# macOS-specific files
.DS_Store
# jetbrains setting folder
.idea/

21
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,21 @@
FROM node:20-slim AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
FROM node:20-slim
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/package.json ./package.json
ENV HOST=0.0.0.0
ENV PORT=4321
EXPOSE 4321
CMD ["node", "./dist/server/entry.mjs"]

43
frontend/README.md Normal file
View File

@@ -0,0 +1,43 @@
# Astro Starter Kit: Minimal
```sh
npm create astro@latest -- --template minimal
```
> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!
## 🚀 Project Structure
Inside of your Astro project, you'll see the following folders and files:
```text
/
├── public/
├── src/
│ └── pages/
│ └── index.astro
└── package.json
```
Astro looks for `.astro` or `.md` files in the `src/pages/` directory. Each page is exposed as a route based on its file name.
There's nothing special about `src/components/`, but that's where we like to put any Astro/React/Vue/Svelte/Preact components.
Any static assets, like images, can be placed in the `public/` directory.
## 🧞 Commands
All commands are run from the root of the project, from a terminal:
| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |
## 👀 Want to learn more?
Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).

17
frontend/astro.config.mjs Normal file
View File

@@ -0,0 +1,17 @@
// @ts-check
import { defineConfig } from 'astro/config';
import tailwindcss from '@tailwindcss/vite';
import node from '@astrojs/node';
// https://astro.build/config
export default defineConfig({
vite: {
plugins: [tailwindcss()]
},
adapter: node({
mode: 'standalone'
})
});

5613
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

22
frontend/package.json Normal file
View File

@@ -0,0 +1,22 @@
{
"name": "frontend",
"type": "module",
"version": "0.0.1",
"engines": {
"node": ">=22.12.0"
},
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@astrojs/node": "^10.0.3",
"@catppuccin/tailwindcss": "^1.0.0",
"@tailwindcss/vite": "^4.2.2",
"astro": "^6.0.8",
"marked": "^17.0.5",
"tailwindcss": "^4.2.2"
}
}

BIN
frontend/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 655 B

View File

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 128 128">
<path d="M50.4 78.5a75.1 75.1 0 0 0-28.5 6.9l24.2-65.7c.7-2 1.9-3.2 3.4-3.2h29c1.5 0 2.7 1.2 3.4 3.2l24.2 65.7s-11.6-7-28.5-7L67 45.5c-.4-1.7-1.6-2.8-2.9-2.8-1.3 0-2.5 1.1-2.9 2.7L50.4 78.5Zm-1.1 28.2Zm-4.2-20.2c-2 6.6-.6 15.8 4.2 20.2a17.5 17.5 0 0 1 .2-.7 5.5 5.5 0 0 1 5.7-4.5c2.8.1 4.3 1.5 4.7 4.7.2 1.1.2 2.3.2 3.5v.4c0 2.7.7 5.2 2.2 7.4a13 13 0 0 0 5.7 4.9v-.3l-.2-.3c-1.8-5.6-.5-9.5 4.4-12.8l1.5-1a73 73 0 0 0 3.2-2.2 16 16 0 0 0 6.8-11.4c.3-2 .1-4-.6-6l-.8.6-1.6 1a37 37 0 0 1-22.4 2.7c-5-.7-9.7-2-13.2-6.2Z" />
<style>
path { fill: #000; }
@media (prefers-color-scheme: dark) {
path { fill: #FFF; }
}
</style>
</svg>

After

Width:  |  Height:  |  Size: 749 B

View File

@@ -0,0 +1,43 @@
---
import '../styles/global.css';
interface Props {
title: string;
}
const { title } = Astro.props;
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="generator" content={Astro.generator} />
<title>{title} | Narlblog</title>
</head>
<body class="bg-base text-text selection:bg-surface2 selection:text-text">
<div class="fixed inset-0 z-[-1] bg-[radial-gradient(ellipse_at_top,_var(--tw-gradient-stops))] from-surface0 via-base to-base"></div>
<nav class="max-w-4xl mx-auto px-6 py-8">
<header class="glass px-6 py-4 flex items-center justify-between">
<a href="/" class="text-2xl font-bold bg-clip-text text-transparent bg-gradient-to-r from-mauve to-blue">
Narlblog
</a>
<div class="flex gap-4">
<a href="/" class="text-subtext0 hover:text-text transition-colors">Home</a>
<a href="https://github.com/narl" target="_blank" class="text-subtext0 hover:text-text transition-colors">About</a>
</div>
</header>
</nav>
<main class="max-w-4xl mx-auto px-6 py-8">
<slot />
</main>
<footer class="max-w-4xl mx-auto px-6 py-8 text-center text-sm text-subtext0">
&copy; {new Date().getFullYear()} Narlblog. Built with Rust & Astro.
</footer>
</body>
</html>

View File

@@ -0,0 +1,77 @@
---
import Layout from '../layouts/Layout.astro';
const API_URL = import.meta.env.PUBLIC_API_URL || 'http://localhost:3000';
interface Post {
slug: string;
}
let posts: Post[] = [];
let error = '';
try {
const response = await fetch(`${API_URL}/api/posts`);
if (response.ok) {
posts = await response.json();
} else {
error = 'Failed to fetch posts';
}
} catch (e) {
error = 'Could not connect to backend';
}
function formatSlug(slug: string) {
return slug
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
---
<Layout title="Home">
<div class="space-y-8">
<section class="text-center py-12">
<h1 class="text-5xl font-extrabold mb-4 bg-clip-text text-transparent bg-gradient-to-r from-mauve via-blue to-teal">
Welcome to my blog
</h1>
<p class="text-subtext1 text-lg max-w-2xl mx-auto">
Thoughts on software, design, and building things with Rust and Astro.
</p>
</section>
<div class="grid gap-6">
{error && (
<div class="glass p-6 text-red text-center border-red/20">
{error}
</div>
)}
{posts.length === 0 && !error && (
<div class="glass p-12 text-center text-subtext0">
<p>No posts found yet. Add some .md files to the data/posts directory!</p>
</div>
)}
{posts.map((post) => (
<a href={`/posts/${post.slug}`} class="group">
<article class="glass p-8 transition-all hover:scale-[1.01] hover:bg-surface0/80 active:scale-[0.99]">
<div class="flex justify-between items-start">
<div>
<h2 class="text-2xl font-bold text-lavender group-hover:text-mauve transition-colors mb-2">
{formatSlug(post.slug)}
</h2>
<p class="text-subtext0">
Read more about {formatSlug(post.slug)}...
</p>
</div>
<div class="text-mauve opacity-0 group-hover:opacity-100 transition-opacity">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
</div>
</div>
</article>
</a>
))}
</div>
</div>
</Layout>

View File

@@ -0,0 +1,64 @@
---
import Layout from '../../layouts/Layout.astro';
import { marked } from 'marked';
const { slug } = Astro.params;
const API_URL = import.meta.env.PUBLIC_API_URL || 'http://localhost:3000';
interface PostDetail {
slug: string;
content: string;
}
let post: PostDetail | null = null;
let html = '';
let error = '';
try {
const response = await fetch(`${API_URL}/api/posts/${slug}`);
if (response.ok) {
post = await response.json();
if (post) {
html = await marked.parse(post.content);
}
} else {
error = 'Post not found';
}
} catch (e) {
error = 'Could not connect to backend';
}
function formatSlug(slug: string) {
return slug
.split('-')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
}
---
<Layout title={post ? formatSlug(post.slug) : 'Post'}>
<article class="glass p-12 mb-12 animate-in fade-in slide-in-from-bottom-4 duration-700">
<header class="mb-12 border-b border-white/5 pb-12">
<a href="/" class="text-blue hover:text-sky transition-colors mb-8 inline-flex items-center gap-2 group">
<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="transition-transform group-hover:-translate-x-1"><path d="m15 18-6-6 6-6"/></svg>
Back to list
</a>
{post && (
<h1 class="text-5xl font-extrabold text-mauve mt-4">
{formatSlug(post.slug)}
</h1>
)}
</header>
{error && (
<div class="text-red text-center py-12">
<h2 class="text-2xl font-bold mb-4">{error}</h2>
<a href="/" class="text-blue underline">Return home</a>
</div>
)}
{post && (
<div class="prose prose-invert max-w-none" set:html={html} />
)}
</article>
</Layout>

View File

@@ -0,0 +1,57 @@
@import "tailwindcss";
@theme {
--color-crust: #11111b;
--color-mantle: #181825;
--color-base: #1e1e2e;
--color-surface0: #313244;
--color-surface1: #45475a;
--color-surface2: #585b70;
--color-overlay0: #6c7086;
--color-overlay1: #7f849c;
--color-overlay2: #9399b2;
--color-text: #cdd6f4;
--color-subtext0: #a6adc8;
--color-subtext1: #bac2de;
--color-blue: #8caaee;
--color-lavender: #b4befe;
--color-sapphire: #85c1dc;
--color-sky: #99d1db;
--color-teal: #81c8be;
--color-green: #a6d189;
--color-yellow: #e5c890;
--color-peach: #ef9f76;
--color-maroon: #ea999c;
--color-red: #e78284;
--color-mauve: #ca9ee6;
--color-pink: #f4b8e4;
--color-flamingo: #eebebe;
--color-rosewater: #f2d5cf;
}
body {
background-color: var(--color-base);
color: var(--color-text);
min-height: 100vh;
}
/* Typography styles for Markdown */
.prose h1 { @apply text-4xl font-bold mb-6 text-mauve; }
.prose h2 { @apply text-3xl font-semibold mb-4 mt-8 text-lavender; }
.prose h3 { @apply text-2xl font-medium mb-3 mt-6 text-blue; }
.prose p { @apply mb-4 leading-relaxed; }
.prose a { @apply text-blue hover:text-sky underline underline-offset-4 decoration-2 decoration-blue/30 hover:decoration-sky transition-colors; }
.prose ul { @apply list-disc list-inside mb-4; }
.prose ol { @apply list-decimal list-inside mb-4; }
.prose blockquote { @apply border-l-4 border-surface2 pl-4 italic text-subtext0 my-6; }
.prose pre { @apply bg-crust p-4 rounded-xl overflow-x-auto border border-white/5 my-6; }
.prose code { @apply bg-surface0 px-1.5 py-0.5 rounded text-sm font-mono text-peach; }
.prose img { @apply max-w-full h-auto rounded-xl shadow-lg border border-white/5 my-8; }
.glass {
background-color: color-mix(in srgb, var(--color-surface0) 60%, transparent);
backdrop-filter: blur(12px);
border: 1px solid rgba(255, 255, 255, 0.05);
box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.5);
border-radius: 1rem;
}

5
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,5 @@
{
"extends": "astro/tsconfigs/strict",
"include": [".astro/types.d.ts", "**/*"],
"exclude": ["dist"]
}