initial commit

This commit is contained in:
Jiao77
2026-03-01 09:13:24 +08:00
commit 72baa341cc
43 changed files with 12560 additions and 0 deletions

117
.gitignore vendored Normal file
View File

@@ -0,0 +1,117 @@
# ===========================================
# NovaBlog .gitignore
# ===========================================
# -------------- Node.js / Astro --------------
# Dependencies
node_modules/
.pnpm-store/
# Build output
dist/
.astro/
# Environment variables
.env
.env.local
.env.*.local
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Editor directories and files
.vscode/*
!.vscode/extensions.json
!.vscode/settings.json
.idea/
*.swp
*.swo
*~
# OS generated files
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
# -------------- Go / Server --------------
# Binary
server/novablog
server/server
*.exe
*.exe~
*.dll
*.so
*.dylib
# Go test coverage
*.out
coverage.txt
# Go vendor
vendor/
# -------------- Database --------------
# SQLite database (runtime data, not source control)
server/data/
*.db
*.db-journal
*.db-wal
*.db-shm
# Keep directory structure but ignore db files
!server/data/.gitkeep
# -------------- Docker --------------
# Docker volumes (if using local bind mounts)
.docker/
# -------------- IDE / Editor --------------
# JetBrains
.idea/
# VSCode
.vscode/
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# Sublime Text
*.sublime-project
*.sublime-workspace
# Vim
*.swp
*.swo
# -------------- Misc --------------
# Temporary files
tmp/
temp/
*.tmp
*.temp
# Backup files
*.bak
*.backup
# Log files
logs/
*.log
# Cache
.cache/
.parcel-cache/
.eslintcache
# Secrets (never commit sensitive data)
*.pem
*.key
secrets/

176
README.md Normal file
View File

@@ -0,0 +1,176 @@
# NovaBlog
🚀 一款面向程序员和极客的极轻量级博客系统,采用"静态渲染 + 轻量级微服务"的解耦架构。
## ✨ 特性
- **极致的排版自由**:原生支持 MDX允许在 Markdown 中直接嵌入 Vue/React 组件和 Typst 复杂学术排版
- **优雅的动态交互**:支持用户注册登录、评论、点赞,但核心页面保持纯静态
- **低资源占用**Go 后端 + SQLite内存占用极低通常十几 MB可在 2C1G 甚至更低配置运行
- **现代化主题系统**基于组件化思想构建CSS 变量换肤,支持暗黑模式
- **Docker 容器化**:一键部署,方便在个人 NAS 或云服务器上运行
## 🏗️ 架构
```
┌─────────────────────────────────────────────────────────┐
│ Nginx │
│ (静态文件服务 + API 反向代理) │
└─────────────────────┬───────────────────────────────────┘
┌─────────────┴─────────────┐
│ │
▼ ▼
┌───────────────┐ ┌───────────────┐
│ Astro 前端 │ │ Go API │
│ (静态 HTML) │◄─────────►│ (Gin + SQLite)│
│ Zero-JS │ HTTP │ ~15MB 内存 │
└───────────────┘ └───────────────┘
```
## 📁 项目结构
```
NovaBlog/
├── src/ # Astro 前端源码
│ ├── components/ # Vue/Astro 组件
│ │ ├── CommentSection.vue # 评论区组件
│ │ ├── LikeButton.vue # 点赞按钮
│ │ ├── Counter.vue # MDX 示例组件
│ │ └── TypstBlock.astro # Typst 渲染组件
│ ├── content/ # 内容集合
│ │ ├── blog/ # 博客文章 (MDX)
│ │ └── config.ts # 内容配置
│ ├── layouts/ # 页面布局
│ │ ├── BaseLayout.astro
│ │ └── PostLayout.astro
│ ├── pages/ # 页面路由
│ └── styles/ # 全局样式
├── server/ # Go 后端源码
│ ├── cmd/server/ # 程序入口
│ ├── internal/
│ │ ├── config/ # 配置管理
│ │ ├── database/ # 数据库连接
│ │ ├── handlers/ # HTTP 处理器
│ │ ├── middleware/ # 中间件
│ │ ├── models/ # 数据模型
│ │ └── utils/ # 工具函数
│ └── Dockerfile
├── docker-compose.yml # Docker 编排
└── nginx.conf # Nginx 配置
```
## 🚀 快速开始
### 开发环境
**前端开发:**
```bash
# 安装依赖
npm install
# 启动开发服务器
npm run dev
# 访问 http://localhost:4321
```
**后端开发:**
```bash
cd server
# 下载依赖
go mod download
# 运行服务
go run ./cmd/server
# API 服务于 http://localhost:8080
```
### 生产部署
```bash
# 1. 构建前端
npm run build
# 2. 启动 Docker 容器
docker-compose up -d
# 访问 http://localhost
```
## 📝 写作
`src/content/blog/` 目录下创建 `.mdx``.md` 文件:
```yaml
---
title: 我的第一篇文章
description: 文章描述
pubDate: 2024-01-01
author: NovaBlog
tags: [博客, 技术]
category: 技术
heroImage: /images/hero.jpg
---
# Hello NovaBlog!
这是一篇使用 MDX 编写的文章...
<!-- 嵌入 Vue 组件 -->
<Counter client:load />
<!-- Typst 数学公式 -->
<TypstBlock code="$ sum_(i=1)^n x_i = x_1 + x_2 + dots + x_n $" />
```
## 🔌 API 接口
### 认证
| 方法 | 路径 | 描述 |
|------|------|------|
| POST | `/api/auth/register` | 用户注册 |
| POST | `/api/auth/login` | 用户登录 |
| GET | `/api/auth/profile` | 获取当前用户信息 (需认证) |
### 评论
| 方法 | 路径 | 描述 |
|------|------|------|
| GET | `/api/comments?post_id=xxx` | 获取文章评论 |
| POST | `/api/comments` | 发表评论 (需认证) |
| DELETE | `/api/comments/:id` | 删除评论 (需认证) |
### 点赞
| 方法 | 路径 | 描述 |
|------|------|------|
| GET | `/api/likes?post_id=xxx` | 获取点赞状态 |
| POST | `/api/likes` | 切换点赞状态 (需认证) |
## 🛠️ 技术栈
**前端:**
- [Astro](https://astro.build/) - 静态站点生成
- [Vue 3](https://vuejs.org/) - 交互组件
- [Tailwind CSS](https://tailwindcss.com/) - 样式
**后端:**
- [Go](https://golang.org/) - 编程语言
- [Gin](https://gin-gonic.com/) - Web 框架
- [GORM](https://gorm.io/) - ORM
- [SQLite](https://www.sqlite.org/) - 数据库
- [JWT](https://jwt.io/) - 认证
**部署:**
- [Docker](https://www.docker.com/) - 容器化
- [Nginx](https://nginx.org/) - 反向代理
## 📜 License
MIT License © 2024

118
TODO Normal file
View File

@@ -0,0 +1,118 @@
# 轻量级混合架构博客系统 (暂定名NovaBlog) 需求及开发文档
## 1. 项目概述
本项目旨在开发一款面向程序员和极客的极轻量级博客系统。针对目前市面上静态博客(如 Hexo排版能力有限、缺乏动态交互以及动态博客如 Halo、WordPress过度商业化、架构臃肿、资源占用高的问题本项目提出一种**“静态渲染 + 轻量级微服务”**的解耦架构。
**核心目标:**
* **极致的排版自由:** 原生支持 MDX允许在 Markdown 中直接嵌入前端组件JS/HTML 动效)和 Typst 复杂学术排版。
* **优雅的动态交互:** 支持用户注册登录、评论、点赞,但核心页面保持纯静态。
* **低资源占用:** 确保应用能在 2C1G 甚至更低配置的云服务器上稳定运行,杜绝周期性 CPU 满载问题,同时支持 Docker 容器化,方便部署在个人 NAS 上。
* **现代化的主题系统:** 基于组件化思想构建主题,实现积木式的页面组合,降低主题开发和迁移成本。
---
## 2. 核心架构设计
系统采用前后端完全解耦的架构,前端负责内容解析与预渲染,后端仅作为无状态的数据 API 提供支持。
### 2.1 表现层 (前端 / Astro)
基于 Astro 框架构建,利用其 Islands Architecture群岛架构特性
* **构建时 (Build Time)** 将 `.md` 和 `.mdx` 文件(包含 Typst 代码块)统一编译为纯静态的 HTML/CSS。
* **运行时 (Client Side)** 大部分页面为 Zero-JS仅在“评论区”、“点赞按钮”等特定“岛屿”组件上挂载 JavaScript 并发起按需 API 请求。
### 2.2 交互层 (后端微服务 / Micro API)
一个极轻量的后端 API 服务,专门处理动态请求。为了绝对的轻量化,避免 JVM 或臃肿 Node 框架带来的内存和 CPU 开销采用轻量级语言或极简框架开发搭配本地文件型数据库SQLite
### 2.3 部署形态
* **前端产物:** 编译后的纯静态文件可托管于任何 CDN、Nginx 容器或 GitHub Pages。
* **后端 API** 打包为轻量级 Docker 镜像,暴露特定端口,通过 Nginx 反向代理提供服务。可轻松接入虚拟局域网作为服务节点。
---
## 3. 功能需求详细说明
### 3.1 内容管理模块 (基于文件系统)
* **本地化撰写:** 以 `src/content/blog/` 目录为核心,通过标准 Markdown 和 Frontmatter (YAML) 管理元数据(标题、日期、标签、分类)。
* **MDX 混合解析:** * 支持标准的 Markdown 语法。
* 支持直接在文章中 `import` 并使用 Vue/React/原生 JS 组件,实现图表、可交互动画等丰富排版。
* **Typst 渲染支持:** 封装 `<TypstBlock />` 组件,在构建阶段调用 Typst 编译器将数学公式和复杂排版渲染为高质量 SVG 嵌入页面。
### 3.2 动态交互模块 (API 驱动)
* **用户鉴权:** * 管理员身份认证(用于后台极简面板或特定 API 调用)。
* 普通用户注册/登录(支持邮箱验证或 OAuth 第三方登录,如 GitHub
* 基于 JWT (JSON Web Token) 的无状态鉴权。
* **评论系统:**
* 支持文章下的多级嵌套评论。
* 支持 Markdown 基础语法解析。
* 前端组件支持 `client:visible` 懒加载,仅当用户滚动到评论区时才加载请求逻辑。
* **点赞系统:**
* 基于文章 ID 和用户 ID (或访客 IP Hash) 的防刷点赞接口。
### 3.3 主题与布局系统 (组件化)
* **Layout 核心:** 提供基础的 `BaseLayout.astro`,定义全局的 Header、Footer 和 SEO Meta 标签。
* **CSS 变量换肤:** 样式层全面采用 CSS Variables通过切换变量配置文件即可实现黑白模式和主题色彩切换。
* **组件插槽 (Slots)** 页面主体留白,通过 Astro 的 `<slot />` 机制允许不同文章复用或重写特定的页面布局。
---
## 4. 技术选型建议
### 4.1 前端 (静态生成与渲染)
* **核心框架:** Astro (提供极速构建、MDX 支持和内容集合强校验)。
* **组件库生态:** Vue 3 或 React (仅用于编写需要动态交互的“岛屿”组件,如评论框)。
* **样式方案:** Tailwind CSS 或纯 CSS 变量 (保持轻量)。
### 4.2 后端 (动态 API 提供)
为了解决小鸡(如 2C1G 配置)资源受限问题,推荐以下两种方案之一:
* **方案 A (性能极致 - 推荐)** **Go 语言 (Gin/Fiber) + SQLite**。编译为二进制文件运行,内存常驻极低(通常十几 MBCPU 开销极小,高并发无压力。
* **方案 B (开发极速)** **Node.js (Hono 或 Fastify) + SQLite + Prisma (ORM)**。比传统的 NestJS 或 Express 轻量得多,生态契合度高。
---
## 5. 阶段开发规划 (Roadmap)
### Phase 1: 核心静态引擎构建 (MVP)
* [ ] 初始化 Astro 项目,配置 Content Collections 数据校验。
* [ ] 编写基础的博客 Layout (主页、文章列表页、文章详情页)。
* [ ] 实现 MDX 支持,编写首个包含动态 HTML 交互组件的测试文章。
* [ ] 封装 Typst 渲染组件,打通构建流。
### Phase 2: 轻量 API 服务开发
* [ ] 搭建后端服务项目,配置 SQLite 数据库和 ORM 模型 (Users, Posts_Meta, Comments)。
* [ ] 实现 JWT 登录与鉴权接口。
* [ ] 实现评论的 CRUD 接口和文章点赞接口。
* [ ] 后端 Docker 化封装。
### Phase 3: 前后端联调与交互组件
* [ ] 在 Astro 中使用 UI 框架 (Vue/React) 开发独立于静态页面的评论区组件。
* [ ] 联调跨域 API处理 Loading、Error 等异步状态。
* [ ] 实现文章页的点赞按钮交互。
### Phase 4: 部署与测试
* [ ] 前端打包测试 (`astro build`),验证打包后的 JS 产物大小。
* [ ] 后端部署至云服务器或 NAS 节点,配置 Nginx 反向代理。
* [ ] 压力测试与 CPU 监控,确保资源占用在合理阈值内。

36
astro.config.mjs Normal file
View File

@@ -0,0 +1,36 @@
// @ts-check
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import vue from '@astrojs/vue';
import tailwind from '@astrojs/tailwind';
// https://astro.build/config
export default defineConfig({
site: 'https://your-domain.com', // 替换为实际域名
integrations: [
mdx({
// 配置 MDX 组件映射
optimize: true,
}),
vue(),
tailwind({
applyBaseStyles: false, // 我们将手动控制基础样式
}),
],
markdown: {
shikiConfig: {
theme: 'github-dark',
wrap: true,
},
},
vite: {
ssr: {
noExternal: ['@vueuse/core'],
},
},
// 配置构建输出
output: 'static',
build: {
assets: 'assets',
},
});

36
docker-compose.yml Normal file
View File

@@ -0,0 +1,36 @@
version: '3.8'
services:
# 前端服务 (Nginx 托管静态文件)
frontend:
image: nginx:alpine
container_name: novablog-frontend
ports:
- "80:80"
volumes:
- ./dist:/usr/share/nginx/html:ro
- ./nginx.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
- api
restart: unless-stopped
# 后端 API 服务
api:
build:
context: ./server
dockerfile: Dockerfile
container_name: novablog-api
ports:
- "8080:8080"
environment:
- GIN_MODE=release
- SERVER_PORT=8080
- DB_PATH=/app/data/novablog.db
- JWT_SECRET=${JWT_SECRET:-your-secret-key-change-me}
- CORS_ORIGIN=${CORS_ORIGIN:-http://localhost}
volumes:
- novablog-data:/app/data
restart: unless-stopped
volumes:
novablog-data:

48
nginx.conf Normal file
View File

@@ -0,0 +1,48 @@
server {
listen 80;
server_name localhost;
# Gzip 压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml;
gzip_min_length 1000;
# 静态文件缓存
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}
# API 反向代理
location /api/ {
proxy_pass http://api:8080/api/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
# 健康检查代理
location /health {
proxy_pass http://api:8080/health;
proxy_http_version 1.1;
proxy_set_header Host $host;
}
# 静态文件服务 (Astro SPA 路由)
location / {
root /usr/share/nginx/html;
try_files $uri $uri/ $uri.html /index.html;
}
# 错误页面
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}

8624
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

20
package.json Normal file
View File

@@ -0,0 +1,20 @@
{
"name": "novablog",
"type": "module",
"version": "0.0.1",
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro"
},
"dependencies": {
"@astrojs/mdx": "^4.3.13",
"@astrojs/tailwind": "^5.1.5",
"@astrojs/vue": "^5.1.4",
"@tailwindcss/typography": "^0.5.19",
"astro": "^5.17.1",
"tailwindcss": "^3.4.0",
"vue": "^3.5.29"
}
}

BIN
public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 655 B

9
public/favicon.svg Normal file
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

43
server/Dockerfile Normal file
View File

@@ -0,0 +1,43 @@
# 构建阶段
FROM golang:1.21-alpine AS builder
WORKDIR /app
# 安装依赖
RUN apk add --no-cache git gcc musl-dev
# 复制 go.mod 和 go.sum
COPY go.mod go.sum ./
# 下载依赖
RUN go mod download
# 复制源代码
COPY . .
# 构建二进制文件
RUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo -o novablog-server ./cmd/server
# 运行阶段
FROM alpine:latest
WORKDIR /app
# 安装 ca-certificates用于 HTTPS 请求)
RUN apk --no-cache add ca-certificates tzdata
# 从构建阶段复制二进制文件
COPY --from=builder /app/novablog-server .
# 创建数据目录
RUN mkdir -p /app/data
# 暴露端口
EXPOSE 8080
# 设置环境变量
ENV GIN_MODE=release
ENV DB_PATH=/app/data/novablog.db
# 运行
CMD ["./novablog-server"]

104
server/cmd/server/main.go Normal file
View File

@@ -0,0 +1,104 @@
package main
import (
"log"
"os"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"github.com/novablog/server/internal/config"
"github.com/novablog/server/internal/database"
"github.com/novablog/server/internal/handlers"
"github.com/novablog/server/internal/middleware"
"github.com/novablog/server/internal/utils"
)
func main() {
// 加载配置
cfg := config.Load()
// 设置运行模式
gin.SetMode(cfg.Server.Mode)
// 初始化数据库
if err := database.Initialize(cfg); err != nil {
log.Fatalf("Failed to initialize database: %v", err)
}
defer database.Close()
// 创建 JWT 管理器
jwtManager := utils.NewJWTManager(cfg.JWT.Secret, cfg.JWT.ExpireTime)
// 创建处理器
authHandler := handlers.NewAuthHandler(jwtManager)
commentHandler := handlers.NewCommentHandler()
likeHandler := handlers.NewLikeHandler()
// 创建路由
r := gin.New()
// 中间件
r.Use(gin.Logger())
r.Use(gin.Recovery())
// CORS 配置
corsConfig := cors.Config{
AllowOrigins: cfg.CORS.AllowOrigins,
AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowHeaders: []string{"Origin", "Content-Type", "Authorization"},
ExposeHeaders: []string{"Content-Length"},
AllowCredentials: true,
}
r.Use(cors.New(corsConfig))
// 健康检查
r.GET("/health", func(c *gin.Context) {
c.JSON(200, gin.H{
"status": "ok",
"message": "NovaBlog API is running",
})
})
// API 路由组
api := r.Group("/api")
{
// 公开接口
api.POST("/auth/register", authHandler.Register)
api.POST("/auth/login", authHandler.Login)
api.GET("/comments", commentHandler.GetComments)
api.POST("/comments", commentHandler.CreateComment) // 允许访客评论
api.GET("/likes", likeHandler.GetLikeStatus)
api.POST("/likes", likeHandler.ToggleLike) // 允许访客点赞(基于 IP Hash
// 需要认证的接口
authGroup := api.Group("")
authGroup.Use(middleware.AuthMiddleware(jwtManager))
{
// 用户相关
authGroup.GET("/auth/profile", authHandler.GetProfile)
authGroup.PUT("/auth/profile", authHandler.UpdateProfile)
// 评论相关(用户删除自己的评论)
authGroup.DELETE("/comments/:id", commentHandler.DeleteComment)
}
// 管理员接口
adminGroup := api.Group("/admin")
adminGroup.Use(middleware.AuthMiddleware(jwtManager))
adminGroup.Use(middleware.AdminMiddleware())
{
// 管理员接口(未来扩展)
}
}
// 启动服务器
port := os.Getenv("PORT")
if port == "" {
port = cfg.Server.Port
}
log.Printf("Server starting on port %s...", port)
if err := r.Run(":" + port); err != nil {
log.Fatalf("Failed to start server: %v", err)
}
}

43
server/go.mod Normal file
View File

@@ -0,0 +1,43 @@
module github.com/novablog/server
go 1.21
require (
github.com/gin-contrib/cors v1.5.0
github.com/gin-gonic/gin v1.9.1
github.com/golang-jwt/jwt/v5 v5.2.0
golang.org/x/crypto v0.21.0
gorm.io/driver/sqlite v1.5.5
gorm.io/gorm v1.25.7
)
require (
github.com/bytedance/sonic v1.10.1 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect
github.com/chenzhuoyu/iasm v0.9.0 // indirect
github.com/gabriel-vasile/mimetype v1.4.2 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.15.5 // indirect
github.com/goccy/go-json v0.10.2 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid/v2 v2.2.5 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.2.4 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.11 // indirect
golang.org/x/arch v0.5.0 // indirect
golang.org/x/net v0.21.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

114
server/go.sum Normal file
View File

@@ -0,0 +1,114 @@
github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM=
github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM=
github.com/bytedance/sonic v1.10.1 h1:7a1wuFXL1cMy7a3f7/VFcEtriuXQnUBhtoVfOZiaysc=
github.com/bytedance/sonic v1.10.1/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4=
github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY=
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk=
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0=
github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA=
github.com/chenzhuoyu/iasm v0.9.0 h1:9fhXjVzq5hUy2gkhhgHl95zG2cEAhw9OSGs8toWWAwo=
github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gabriel-vasile/mimetype v1.4.2 h1:w5qFW6JKBz9Y393Y4q372O9A7cUSequkh1Q7OhCmWKU=
github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA=
github.com/gin-contrib/cors v1.5.0 h1:DgGKV7DDoOn36DFkNtbHrjoRiT5ExCe+PC9/xp7aKvk=
github.com/gin-contrib/cors v1.5.0/go.mod h1:TvU7MAZ3EwrPLI2ztzTt3tqgvBCq+wn8WpZmfADjupI=
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg=
github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
github.com/go-playground/validator/v10 v10.15.5 h1:LEBecTWb/1j5TNY1YYG2RcOUN3R7NLylN+x8TTueE24=
github.com/go-playground/validator/v10 v10.15.5/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU=
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
github.com/golang-jwt/jwt/v5 v5.2.0 h1:d/ix8ftRUorsN+5eMIlF4T6J8CAt9rch3My2winC1Jw=
github.com/golang-jwt/jwt/v5 v5.2.0/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
github.com/klauspost/cpuid/v2 v2.2.5 h1:0E5MSMDEoAulmXNFquVs//DdoomxaoTY1kUhbc/qbZg=
github.com/klauspost/cpuid/v2 v2.2.5/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q=
github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4=
github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
github.com/ugorji/go/codec v1.2.11 h1:BMaWp1Bb6fHwEtbplGBGJ498wD+LKlNSl25MjdZY4dU=
github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/arch v0.5.0 h1:jpGode6huXQxcskEIpOCvrU+tzo81b6+oFLUYXWtH/Y=
golang.org/x/arch v0.5.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E=
gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE=
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

View File

@@ -0,0 +1,74 @@
package config
import (
"os"
"strconv"
)
// Config 应用配置
type Config struct {
Server ServerConfig
Database DatabaseConfig
JWT JWTConfig
CORS CORSConfig
}
// ServerConfig 服务器配置
type ServerConfig struct {
Port string
Mode string // debug, release, test
}
// DatabaseConfig 数据库配置
type DatabaseConfig struct {
Path string
}
// JWTConfig JWT 配置
type JWTConfig struct {
Secret string
ExpireTime int // 过期时间(小时)
}
// CORSConfig CORS 配置
type CORSConfig struct {
AllowOrigins []string
}
// Load 从环境变量加载配置
func Load() *Config {
return &Config{
Server: ServerConfig{
Port: getEnv("SERVER_PORT", "8080"),
Mode: getEnv("GIN_MODE", "release"),
},
Database: DatabaseConfig{
Path: getEnv("DB_PATH", "./data/novablog.db"),
},
JWT: JWTConfig{
Secret: getEnv("JWT_SECRET", "novablog-secret-key-change-in-production"),
ExpireTime: getEnvAsInt("JWT_EXPIRE_HOURS", 24*7), // 默认 7 天
},
CORS: CORSConfig{
AllowOrigins: []string{
getEnv("CORS_ORIGIN", "http://localhost:4321"),
},
},
}
}
func getEnv(key, defaultValue string) string {
if value := os.Getenv(key); value != "" {
return value
}
return defaultValue
}
func getEnvAsInt(key string, defaultValue int) int {
if value := os.Getenv(key); value != "" {
if intValue, err := strconv.Atoi(value); err == nil {
return intValue
}
}
return defaultValue
}

View File

@@ -0,0 +1,61 @@
package database
import (
"fmt"
"os"
"path/filepath"
"github.com/novablog/server/internal/config"
"github.com/novablog/server/internal/models"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
var DB *gorm.DB
// Initialize 初始化数据库连接
func Initialize(cfg *config.Config) error {
var err error
// 确保数据目录存在
dbDir := filepath.Dir(cfg.Database.Path)
if err := os.MkdirAll(dbDir, 0755); err != nil {
return fmt.Errorf("failed to create database directory: %w", err)
}
// 连接 SQLite 数据库
DB, err = gorm.Open(sqlite.Open(cfg.Database.Path), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
return fmt.Errorf("failed to connect database: %w", err)
}
// 自动迁移数据库表
if err := autoMigrate(); err != nil {
return fmt.Errorf("failed to migrate database: %w", err)
}
return nil
}
// autoMigrate 自动迁移数据库表结构
func autoMigrate() error {
return DB.AutoMigrate(
&models.User{},
&models.Comment{},
&models.Like{},
&models.LikeCount{},
&models.PostMeta{},
)
}
// Close 关闭数据库连接
func Close() error {
sqlDB, err := DB.DB()
if err != nil {
return err
}
return sqlDB.Close()
}

View File

@@ -0,0 +1,195 @@
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/novablog/server/internal/database"
"github.com/novablog/server/internal/middleware"
"github.com/novablog/server/internal/models"
"github.com/novablog/server/internal/utils"
"gorm.io/gorm"
)
// AuthHandler 认证处理器
type AuthHandler struct {
jwtManager *utils.JWTManager
}
// NewAuthHandler 创建认证处理器
func NewAuthHandler(jwtManager *utils.JWTManager) *AuthHandler {
return &AuthHandler{
jwtManager: jwtManager,
}
}
// RegisterRequest 注册请求
type RegisterRequest struct {
Username string `json:"username" binding:"required,min=3,max=50"`
Email string `json:"email" binding:"required,email"`
Password string `json:"password" binding:"required,min=6,max=50"`
Nickname string `json:"nickname"`
}
// LoginRequest 登录请求
type LoginRequest struct {
Username string `json:"username" binding:"required"`
Password string `json:"password" binding:"required"`
}
// AuthResponse 认证响应
type AuthResponse struct {
Token string `json:"token"`
User models.User `json:"user"`
}
// Register 用户注册
func (h *AuthHandler) Register(c *gin.Context) {
var req RegisterRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 检查用户名是否已存在
var existingUser models.User
if err := database.DB.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
c.JSON(http.StatusConflict, gin.H{"error": "username already exists"})
return
}
// 检查邮箱是否已存在
if err := database.DB.Where("email = ?", req.Email).First(&existingUser).Error; err == nil {
c.JSON(http.StatusConflict, gin.H{"error": "email already exists"})
return
}
// 哈希密码
hashedPassword, err := utils.HashPassword(req.Password)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to hash password"})
return
}
// 创建用户
user := models.User{
Username: req.Username,
Email: req.Email,
Password: hashedPassword,
Nickname: req.Nickname,
Role: "user",
}
if err := database.DB.Create(&user).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create user"})
return
}
// 生成 Token
token, err := h.jwtManager.GenerateToken(user.ID, user.Username, user.Role)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
return
}
c.JSON(http.StatusCreated, AuthResponse{
Token: token,
User: user,
})
}
// Login 用户登录
func (h *AuthHandler) Login(c *gin.Context) {
var req LoginRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 查找用户(支持用户名或邮箱登录)
var user models.User
if err := database.DB.Where("username = ? OR email = ?", req.Username, req.Username).First(&user).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
return
}
// 验证密码
if !utils.CheckPassword(req.Password, user.Password) {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
return
}
// 生成 Token
token, err := h.jwtManager.GenerateToken(user.ID, user.Username, user.Role)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to generate token"})
return
}
c.JSON(http.StatusOK, AuthResponse{
Token: token,
User: user,
})
}
// GetProfile 获取当前用户信息
func (h *AuthHandler) GetProfile(c *gin.Context) {
userID, _ := middleware.GetUserID(c)
var user models.User
if err := database.DB.First(&user, userID).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "user not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
return
}
c.JSON(http.StatusOK, user)
}
// UpdateProfileRequest 更新用户信息请求
type UpdateProfileRequest struct {
Nickname string `json:"nickname"`
Avatar string `json:"avatar"`
Bio string `json:"bio"`
}
// UpdateProfile 更新用户信息
func (h *AuthHandler) UpdateProfile(c *gin.Context) {
userID, _ := middleware.GetUserID(c)
var req UpdateProfileRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 更新用户信息
updates := map[string]interface{}{}
if req.Nickname != "" {
updates["nickname"] = req.Nickname
}
if req.Avatar != "" {
updates["avatar"] = req.Avatar
}
if req.Bio != "" {
updates["bio"] = req.Bio
}
if err := database.DB.Model(&models.User{}).Where("id = ?", userID).Updates(updates).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update profile"})
return
}
// 返回更新后的用户信息
var user models.User
database.DB.First(&user, userID)
c.JSON(http.StatusOK, user)
}

View File

@@ -0,0 +1,141 @@
package handlers
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/novablog/server/internal/database"
"github.com/novablog/server/internal/middleware"
"github.com/novablog/server/internal/models"
"gorm.io/gorm"
)
// CommentHandler 评论处理器
type CommentHandler struct{}
// NewCommentHandler 创建评论处理器
func NewCommentHandler() *CommentHandler {
return &CommentHandler{}
}
// CreateCommentRequest 创建评论请求
type CreateCommentRequest struct {
PostID string `json:"post_id" binding:"required"`
ParentID *uint `json:"parent_id"`
Content string `json:"content" binding:"required,min=1,max=2000"`
}
// CreateComment 创建评论
func (h *CommentHandler) CreateComment(c *gin.Context) {
userID, _ := middleware.GetUserID(c)
var req CreateCommentRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
comment := models.Comment{
PostID: req.PostID,
UserID: userID,
ParentID: req.ParentID,
Content: req.Content,
Status: "approved", // 默认直接通过,可改为 pending 需审核
}
if err := database.DB.Create(&comment).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create comment"})
return
}
// 加载用户信息
database.DB.Preload("User").First(&comment, comment.ID)
c.JSON(http.StatusCreated, comment)
}
// GetComments 获取文章评论列表
func (h *CommentHandler) GetComments(c *gin.Context) {
postID := c.Query("post_id")
if postID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "post_id is required"})
return
}
// 分页参数
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
if page < 1 {
page = 1
}
if pageSize < 1 || pageSize > 100 {
pageSize = 20
}
// 获取顶级评论(非回复)
var comments []models.Comment
var total int64
query := database.DB.Model(&models.Comment{}).
Where("post_id = ? AND status = ? AND parent_id IS NULL", postID, "approved")
query.Count(&total)
if err := query.Preload("User").
Preload("Replies.User").
Order("created_at DESC").
Offset((page - 1) * pageSize).
Limit(pageSize).
Find(&comments).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to get comments"})
return
}
c.JSON(http.StatusOK, gin.H{
"data": comments,
"pagination": gin.H{
"page": page,
"page_size": pageSize,
"total": total,
"total_page": (total + int64(pageSize) - 1) / int64(pageSize),
},
})
}
// DeleteComment 删除评论(仅限本人或管理员)
func (h *CommentHandler) DeleteComment(c *gin.Context) {
userID, _ := middleware.GetUserID(c)
role, _ := c.Get("role")
idStr := c.Param("id")
id, err := strconv.ParseUint(idStr, 10, 32)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid comment id"})
return
}
var comment models.Comment
if err := database.DB.First(&comment, id).Error; err != nil {
if err == gorm.ErrRecordNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "comment not found"})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
return
}
// 检查权限:本人或管理员可删除
if comment.UserID != userID && role != "admin" {
c.JSON(http.StatusForbidden, gin.H{"error": "permission denied"})
return
}
// 软删除
if err := database.DB.Delete(&comment).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete comment"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "comment deleted"})
}

View File

@@ -0,0 +1,169 @@
package handlers
import (
"crypto/sha256"
"encoding/hex"
"net/http"
"github.com/gin-gonic/gin"
"github.com/novablog/server/internal/database"
"github.com/novablog/server/internal/middleware"
"github.com/novablog/server/internal/models"
"gorm.io/gorm"
)
// LikeHandler 点赞处理器
type LikeHandler struct{}
// NewLikeHandler 创建点赞处理器
func NewLikeHandler() *LikeHandler {
return &LikeHandler{}
}
// LikeRequest 点赞请求
type LikeRequest struct {
PostID string `json:"post_id" binding:"required"`
}
// LikeResponse 点赞响应
type LikeResponse struct {
Liked bool `json:"liked"`
LikeCount int `json:"like_count"`
}
// ToggleLike 切换点赞状态(点赞/取消点赞)
func (h *LikeHandler) ToggleLike(c *gin.Context) {
var req LikeRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// 获取用户 ID可选支持未登录用户
userID, isLoggedIn := middleware.GetUserID(c)
// 获取访客 IP Hash用于未登录用户的防刷
ipHash := ""
if !isLoggedIn {
ip := c.ClientIP()
hash := sha256.Sum256([]byte(ip + "novablog-salt")) // 加盐防止反向推导
ipHash = hex.EncodeToString(hash[:])[:64]
}
// 检查是否已点赞
var existingLike models.Like
var err error
if isLoggedIn {
err = database.DB.Where("post_id = ? AND user_id = ?", req.PostID, userID).First(&existingLike).Error
} else {
err = database.DB.Where("post_id = ? AND ip_hash = ?", req.PostID, ipHash).First(&existingLike).Error
}
liked := false
if err == gorm.ErrRecordNotFound {
// 未点赞,创建点赞记录
like := models.Like{
PostID: req.PostID,
IPHash: ipHash,
}
if isLoggedIn {
like.UserID = &userID
}
if err := database.DB.Create(&like).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to like"})
return
}
liked = true
// 更新点赞计数
h.updateLikeCount(req.PostID, 1)
} else if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "database error"})
return
} else {
// 已点赞,取消点赞
if err := database.DB.Delete(&existingLike).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to unlike"})
return
}
liked = false
// 更新点赞计数
h.updateLikeCount(req.PostID, -1)
}
// 获取当前点赞数
likeCount := h.getLikeCount(req.PostID)
c.JSON(http.StatusOK, LikeResponse{
Liked: liked,
LikeCount: likeCount,
})
}
// GetLikeStatus 获取点赞状态
func (h *LikeHandler) GetLikeStatus(c *gin.Context) {
postID := c.Query("post_id")
if postID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "post_id is required"})
return
}
// 获取用户 ID可选
userID, isLoggedIn := middleware.GetUserID(c)
// 获取访客 IP Hash
ipHash := ""
if !isLoggedIn {
ip := c.ClientIP()
hash := sha256.Sum256([]byte(ip + "novablog-salt"))
ipHash = hex.EncodeToString(hash[:])[:64]
}
// 检查是否已点赞
var existingLike models.Like
var err error
if isLoggedIn {
err = database.DB.Where("post_id = ? AND user_id = ?", postID, userID).First(&existingLike).Error
} else {
err = database.DB.Where("post_id = ? AND ip_hash = ?", postID, ipHash).First(&existingLike).Error
}
liked := err == nil
// 获取点赞数
likeCount := h.getLikeCount(postID)
c.JSON(http.StatusOK, LikeResponse{
Liked: liked,
LikeCount: likeCount,
})
}
// updateLikeCount 更新点赞计数
func (h *LikeHandler) updateLikeCount(postID string, delta int) {
var likeCount models.LikeCount
result := database.DB.FirstOrCreate(&likeCount, models.LikeCount{PostID: postID})
if result.Error != nil {
return
}
likeCount.Count += delta
if likeCount.Count < 0 {
likeCount.Count = 0
}
database.DB.Save(&likeCount)
}
// getLikeCount 获取点赞数
func (h *LikeHandler) getLikeCount(postID string) int {
var likeCount models.LikeCount
if err := database.DB.Where("post_id = ?", postID).First(&likeCount).Error; err != nil {
return 0
}
return likeCount.Count
}

View File

@@ -0,0 +1,86 @@
package middleware
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/novablog/server/internal/utils"
)
// AuthMiddleware JWT 认证中间件
func AuthMiddleware(jwtManager *utils.JWTManager) gin.HandlerFunc {
return func(c *gin.Context) {
// 从 Header 获取 Token
authHeader := c.GetHeader("Authorization")
if authHeader == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "authorization header is required",
})
c.Abort()
return
}
// 解析 Bearer Token
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "invalid authorization header format",
})
c.Abort()
return
}
tokenString := parts[1]
// 验证 Token
claims, err := jwtManager.ParseToken(tokenString)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"error": err.Error(),
})
c.Abort()
return
}
// 将用户信息存入上下文
c.Set("userID", claims.UserID)
c.Set("username", claims.Username)
c.Set("role", claims.Role)
c.Next()
}
}
// AdminMiddleware 管理员权限中间件
func AdminMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
role, exists := c.Get("role")
if !exists || role != "admin" {
c.JSON(http.StatusForbidden, gin.H{
"error": "admin permission required",
})
c.Abort()
return
}
c.Next()
}
}
// GetUserID 从上下文获取用户 ID
func GetUserID(c *gin.Context) (uint, bool) {
userID, exists := c.Get("userID")
if !exists {
return 0, false
}
return userID.(uint), true
}
// GetUsername 从上下文获取用户名
func GetUsername(c *gin.Context) (string, bool) {
username, exists := c.Get("username")
if !exists {
return "", false
}
return username.(string), true
}

View File

@@ -0,0 +1,64 @@
package models
import (
"time"
"gorm.io/gorm"
)
// User 用户模型
type User struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
Username string `json:"username" gorm:"uniqueIndex;size:50;not null"`
Email string `json:"email" gorm:"uniqueIndex;size:100;not null"`
Password string `json:"-" gorm:"size:255;not null"` // 不返回给前端
Nickname string `json:"nickname" gorm:"size:50"`
Avatar string `json:"avatar" gorm:"size:255"`
Role string `json:"role" gorm:"size:20;default:'user'"` // admin, user
Bio string `json:"bio" gorm:"size:500"`
Comments []Comment `json:"-" gorm:"foreignKey:UserID"`
Likes []Like `json:"-" gorm:"foreignKey:UserID"`
}
// Comment 评论模型
type Comment struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
PostID string `json:"post_id" gorm:"index;size:100;not null"` // 文章 IDslug
UserID uint `json:"user_id" gorm:"index;not null"`
ParentID *uint `json:"parent_id" gorm:"index"` // 父评论 ID用于嵌套回复
Content string `json:"content" gorm:"type:text;not null"`
Status string `json:"status" gorm:"size:20;default:'approved'"` // pending, approved, spam
User User `json:"user" gorm:"foreignKey:UserID"`
Replies []Comment `json:"replies,omitempty" gorm:"foreignKey:ParentID"`
}
// Like 点赞模型
type Like struct {
ID uint `json:"id" gorm:"primaryKey"`
CreatedAt time.Time `json:"created_at"`
PostID string `json:"post_id" gorm:"uniqueIndex:idx_post_user;size:100;not null"` // 文章 ID
UserID *uint `json:"user_id" gorm:"uniqueIndex:idx_post_user;index"` // 登录用户 ID
IPHash string `json:"-" gorm:"uniqueIndex:idx_post_ip;size:64"` // 访客 IP Hash
}
// LikeCount 文章点赞计数(缓存表)
type LikeCount struct {
PostID string `json:"post_id" gorm:"primaryKey;size:100"`
Count int `json:"count" gorm:"default:0"`
}
// PostMeta 文章元数据(可选,用于存储文章额外信息)
type PostMeta struct {
ID uint `json:"id" gorm:"primaryKey"`
PostID string `json:"post_id" gorm:"uniqueIndex;size:100;not null"`
ViewCount int `json:"view_count" gorm:"default:0"`
LikeCount int `json:"like_count" gorm:"default:0"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}

View File

@@ -0,0 +1,80 @@
package utils
import (
"errors"
"time"
"github.com/golang-jwt/jwt/v5"
)
var (
ErrInvalidToken = errors.New("invalid token")
ErrExpiredToken = errors.New("token has expired")
)
// Claims JWT 声明
type Claims struct {
UserID uint `json:"user_id"`
Username string `json:"username"`
Role string `json:"role"`
jwt.RegisteredClaims
}
// JWTConfig JWT 配置
type JWTConfig struct {
Secret string
ExpireTime int // 过期时间(小时)
}
// JWTManager JWT 管理器
type JWTManager struct {
config JWTConfig
}
// NewJWTManager 创建 JWT 管理器
func NewJWTManager(secret string, expireTime int) *JWTManager {
return &JWTManager{
config: JWTConfig{
Secret: secret,
ExpireTime: expireTime,
},
}
}
// GenerateToken 生成 JWT Token
func (m *JWTManager) GenerateToken(userID uint, username, role string) (string, error) {
claims := &Claims{
UserID: userID,
Username: username,
Role: role,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(m.config.ExpireTime) * time.Hour)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
Issuer: "novablog",
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(m.config.Secret))
}
// ParseToken 解析 JWT Token
func (m *JWTManager) ParseToken(tokenString string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(m.config.Secret), nil
})
if err != nil {
if errors.Is(err, jwt.ErrTokenExpired) {
return nil, ErrExpiredToken
}
return nil, ErrInvalidToken
}
if claims, ok := token.Claims.(*Claims); ok && token.Valid {
return claims, nil
}
return nil, ErrInvalidToken
}

View File

@@ -0,0 +1,20 @@
package utils
import (
"golang.org/x/crypto/bcrypt"
)
// HashPassword 对密码进行哈希
func HashPassword(password string) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
if err != nil {
return "", err
}
return string(bytes), nil
}
// CheckPassword 验证密码
func CheckPassword(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}

View File

@@ -0,0 +1,297 @@
<template>
<div class="comment-section">
<h3 class="text-xl font-bold mb-6">评论</h3>
<!-- 评论输入框 -->
<div v-if="isLoggedIn" class="mb-8">
<textarea
v-model="newComment"
placeholder="写下你的评论..."
class="w-full p-4 border border-border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none"
rows="4"
></textarea>
<div class="flex justify-end mt-2">
<button
@click="submitComment"
:disabled="!newComment.trim() || submitting"
class="btn-primary disabled:opacity-50 disabled:cursor-not-allowed"
>
{{ submitting ? '发布中...' : '发布评论' }}
</button>
</div>
</div>
<!-- 未登录提示 -->
<div v-else class="mb-8 p-4 bg-muted rounded-lg text-center">
<p class="text-foreground/60">
<a href="/login" class="text-primary-500 hover:underline">登录</a> 后参与评论
</p>
</div>
<!-- 评论列表 -->
<div v-if="loading" class="text-center py-8">
<div class="animate-spin w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full mx-auto"></div>
<p class="mt-2 text-foreground/40">加载评论中...</p>
</div>
<div v-else-if="comments.length === 0" class="text-center py-8 text-foreground/40">
<p>暂无评论来抢沙发吧</p>
</div>
<div v-else class="space-y-6">
<div v-for="comment in comments" :key="comment.id" class="comment-item">
<div class="flex gap-4">
<!-- 头像 -->
<div class="flex-shrink-0">
<div class="w-10 h-10 rounded-full bg-primary-100 dark:bg-primary-900 flex items-center justify-center">
<span class="text-primary-600 dark:text-primary-400 font-medium">
{{ (comment.user.nickname || comment.user.username)[0].toUpperCase() }}
</span>
</div>
</div>
<!-- 内容 -->
<div class="flex-1 min-w-0">
<div class="flex items-center gap-2 mb-1">
<span class="font-medium">{{ comment.user.nickname || comment.user.username }}</span>
<span class="text-xs text-foreground/40">{{ formatDate(comment.created_at) }}</span>
</div>
<p class="text-foreground/80 whitespace-pre-wrap">{{ comment.content }}</p>
<!-- 回复按钮 -->
<button
@click="replyTo = comment.id"
class="text-sm text-primary-500 hover:underline mt-2"
>
回复
</button>
</div>
</div>
<!-- 回复输入框 -->
<div v-if="replyTo === comment.id" class="mt-4 ml-14">
<textarea
v-model="replyContent"
placeholder="写下你的回复..."
class="w-full p-3 border border-border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary-500 resize-none text-sm"
rows="3"
></textarea>
<div class="flex justify-end gap-2 mt-2">
<button @click="replyTo = null" class="btn-secondary text-sm">取消</button>
<button
@click="submitReply(comment.id)"
:disabled="!replyContent.trim() || submitting"
class="btn-primary text-sm disabled:opacity-50"
>
回复
</button>
</div>
</div>
<!-- 子评论 -->
<div v-if="comment.replies && comment.replies.length > 0" class="mt-4 ml-14 space-y-4">
<div v-for="reply in comment.replies" :key="reply.id" class="flex gap-3">
<div class="flex-shrink-0">
<div class="w-8 h-8 rounded-full bg-primary-100 dark:bg-primary-900 flex items-center justify-center">
<span class="text-primary-600 dark:text-primary-400 text-sm font-medium">
{{ (reply.user.nickname || reply.user.username)[0].toUpperCase() }}
</span>
</div>
</div>
<div class="flex-1">
<div class="flex items-center gap-2 mb-1">
<span class="font-medium text-sm">{{ reply.user.nickname || reply.user.username }}</span>
<span class="text-xs text-foreground/40">{{ formatDate(reply.created_at) }}</span>
</div>
<p class="text-foreground/80 text-sm">{{ reply.content }}</p>
</div>
</div>
</div>
</div>
</div>
<!-- 分页 -->
<div v-if="pagination.totalPage > 1" class="flex justify-center gap-2 mt-8">
<button
@click="loadPage(pagination.page - 1)"
:disabled="pagination.page <= 1"
class="btn-secondary disabled:opacity-50"
>
上一页
</button>
<span class="px-4 py-2 text-foreground/60">
{{ pagination.page }} / {{ pagination.totalPage }}
</span>
<button
@click="loadPage(pagination.page + 1)"
:disabled="pagination.page >= pagination.totalPage"
class="btn-secondary disabled:opacity-50"
>
下一页
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
const props = defineProps<{
postId: string;
apiBaseUrl?: string;
}>();
const apiBaseUrl = props.apiBaseUrl || 'http://localhost:8080/api';
// 状态
const comments = ref<any[]>([]);
const loading = ref(true);
const submitting = ref(false);
const newComment = ref('');
const replyTo = ref<number | null>(null);
const replyContent = ref('');
const pagination = ref({
page: 1,
pageSize: 20,
total: 0,
totalPage: 0,
});
// 计算属性 - 仅在浏览器环境中访问 localStorage
const isLoggedIn = computed(() => {
if (typeof window === 'undefined') return false;
return !!localStorage.getItem('token');
});
// 获取认证头
function getAuthHeaders(): Record<string, string> {
if (typeof window === 'undefined') return {};
const token = localStorage.getItem('token');
return token ? { Authorization: `Bearer ${token}` } : {};
}
// 加载评论
async function loadComments() {
loading.value = true;
try {
const response = await fetch(
`${apiBaseUrl}/comments?post_id=${props.postId}&page=${pagination.value.page}&page_size=${pagination.value.pageSize}`
);
const data = await response.json();
if (response.ok) {
comments.value = data.data;
pagination.value = data.pagination;
}
} catch (error) {
console.error('Failed to load comments:', error);
} finally {
loading.value = false;
}
}
// 提交评论
async function submitComment() {
if (!newComment.value.trim()) return;
submitting.value = true;
try {
const response = await fetch(`${apiBaseUrl}/comments`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({
post_id: props.postId,
content: newComment.value,
}),
});
if (response.ok) {
newComment.value = '';
await loadComments();
} else {
const error = await response.json();
alert(error.error || '发布失败');
}
} catch (error) {
console.error('Failed to submit comment:', error);
alert('发布失败,请稍后重试');
} finally {
submitting.value = false;
}
}
// 提交回复
async function submitReply(parentId: number) {
if (!replyContent.value.trim()) return;
submitting.value = true;
try {
const response = await fetch(`${apiBaseUrl}/comments`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({
post_id: props.postId,
parent_id: parentId,
content: replyContent.value,
}),
});
if (response.ok) {
replyContent.value = '';
replyTo.value = null;
await loadComments();
} else {
const error = await response.json();
alert(error.error || '回复失败');
}
} catch (error) {
console.error('Failed to submit reply:', error);
alert('回复失败,请稍后重试');
} finally {
submitting.value = false;
}
}
// 加载指定页
function loadPage(page: number) {
pagination.value.page = page;
loadComments();
}
// 格式化日期
function formatDate(dateString: string) {
const date = new Date(dateString);
const now = new Date();
const diff = now.getTime() - date.getTime();
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(diff / 3600000);
const days = Math.floor(diff / 86400000);
if (minutes < 1) return '刚刚';
if (minutes < 60) return `${minutes} 分钟前`;
if (hours < 24) return `${hours} 小时前`;
if (days < 30) return `${days} 天前`;
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
}
onMounted(() => {
loadComments();
});
</script>
<style scoped>
.comment-section {
@apply mt-12 pt-8 border-t border-border;
}
</style>

View File

@@ -0,0 +1,23 @@
<template>
<div class="inline-flex items-center gap-4 px-4 py-2 bg-primary-100 dark:bg-primary-900 rounded-lg">
<button
@click="count--"
class="w-8 h-8 flex items-center justify-center rounded-full bg-primary-500 text-white hover:bg-primary-600 transition-colors"
>
-
</button>
<span class="text-2xl font-bold min-w-[2rem] text-center">{{ count }}</span>
<button
@click="count++"
class="w-8 h-8 flex items-center justify-center rounded-full bg-primary-500 text-white hover:bg-primary-600 transition-colors"
>
+
</button>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const count = ref(0);
</script>

View File

@@ -0,0 +1,134 @@
<template>
<button
@click="toggleLike"
:disabled="loading"
class="like-button flex items-center gap-2 px-4 py-2 rounded-full transition-all duration-300"
:class="[
liked
? 'bg-red-100 dark:bg-red-900/30 text-red-500'
: 'bg-muted hover:bg-red-50 dark:hover:bg-red-900/20 text-foreground/60 hover:text-red-500'
]"
>
<!-- 心形图标 -->
<svg
class="w-5 h-5 transition-transform duration-300"
:class="{ 'scale-125': animating }"
viewBox="0 0 24 24"
fill="currentColor"
>
<path
d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"
/>
</svg>
<!-- 点赞数 -->
<span class="font-medium">{{ likeCount }}</span>
</button>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
const props = defineProps<{
postId: string;
apiBaseUrl?: string;
}>();
const emit = defineEmits<{
(e: 'update', liked: boolean, count: number): void;
}>();
const apiBaseUrl = props.apiBaseUrl || 'http://localhost:8080/api';
// 状态
const liked = ref(false);
const likeCount = ref(0);
const loading = ref(false);
const animating = ref(false);
// 获取认证头
function getAuthHeaders(): Record<string, string> {
// 仅在浏览器环境中访问 localStorage
if (typeof window === 'undefined') return {};
const token = localStorage.getItem('token');
return token ? { Authorization: `Bearer ${token}` } : {};
}
// 加载点赞状态
async function loadLikeStatus() {
loading.value = true;
try {
const response = await fetch(
`${apiBaseUrl}/likes?post_id=${props.postId}`,
{
headers: getAuthHeaders(),
}
);
if (response.ok) {
const data = await response.json();
liked.value = data.liked;
likeCount.value = data.like_count;
}
} catch (error) {
console.error('Failed to load like status:', error);
} finally {
loading.value = false;
}
}
// 切换点赞
async function toggleLike() {
loading.value = true;
try {
const response = await fetch(`${apiBaseUrl}/likes`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...getAuthHeaders(),
},
body: JSON.stringify({
post_id: props.postId,
}),
});
if (response.ok) {
const data = await response.json();
liked.value = data.liked;
likeCount.value = data.like_count;
// 触发动画
if (data.liked) {
animating.value = true;
setTimeout(() => {
animating.value = false;
}, 300);
}
emit('update', data.liked, data.like_count);
} else {
const error = await response.json();
console.error('Failed to toggle like:', error);
}
} catch (error) {
console.error('Failed to toggle like:', error);
} finally {
loading.value = false;
}
}
onMounted(() => {
loadLikeStatus();
});
</script>
<style scoped>
.like-button {
@apply cursor-pointer select-none;
}
.like-button:disabled {
@apply cursor-wait;
}
</style>

View File

@@ -0,0 +1,305 @@
<template>
<div class="login-container">
<div class="login-card">
<div class="tabs">
<button
:class="['tab', { active: mode === 'login' }]"
@click="mode = 'login'"
>
登录
</button>
<button
:class="['tab', { active: mode === 'register' }]"
@click="mode = 'register'"
>
注册
</button>
</div>
<form @submit.prevent="handleSubmit" class="form">
<div class="form-group">
<label for="username">用户名</label>
<input
id="username"
v-model="form.username"
type="text"
placeholder="请输入用户名"
required
/>
</div>
<div class="form-group" v-if="mode === 'register'">
<label for="email">邮箱</label>
<input
id="email"
v-model="form.email"
type="email"
placeholder="请输入邮箱"
required
/>
</div>
<div class="form-group">
<label for="password">密码</label>
<input
id="password"
v-model="form.password"
type="password"
placeholder="请输入密码"
required
/>
</div>
<div class="form-group" v-if="mode === 'register'">
<label for="confirmPassword">确认密码</label>
<input
id="confirmPassword"
v-model="form.confirmPassword"
type="password"
placeholder="请再次输入密码"
required
/>
</div>
<div v-if="error" class="error-message">{{ error }}</div>
<div v-if="success" class="success-message">{{ success }}</div>
<button type="submit" class="submit-btn" :disabled="loading">
{{ loading ? '处理中...' : (mode === 'login' ? '登录' : '注册') }}
</button>
</form>
<div class="divider">
<span></span>
</div>
<button class="github-btn" @click="handleGithubLogin">
<svg viewBox="0 0 24 24" width="20" height="20">
<path fill="currentColor" d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
</svg>
使用 GitHub 登录
</button>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, reactive } from 'vue'
const mode = ref<'login' | 'register'>('login')
const loading = ref(false)
const error = ref('')
const success = ref('')
const form = reactive({
username: '',
email: '',
password: '',
confirmPassword: ''
})
const API_BASE = import.meta.env.PUBLIC_API_BASE || 'http://localhost:8080'
async function handleSubmit() {
error.value = ''
success.value = ''
if (mode.value === 'register' && form.password !== form.confirmPassword) {
error.value = '两次输入的密码不一致'
return
}
loading.value = true
try {
const endpoint = mode.value === 'login' ? '/api/auth/login' : '/api/auth/register'
const body = mode.value === 'login'
? { username: form.username, password: form.password }
: { username: form.username, email: form.email, password: form.password }
const response = await fetch(`${API_BASE}${endpoint}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body)
})
const data = await response.json()
if (!response.ok) {
error.value = data.error || '操作失败'
return
}
if (data.token) {
localStorage.setItem('token', data.token)
localStorage.setItem('user', JSON.stringify(data.user))
success.value = mode.value === 'login' ? '登录成功!' : '注册成功!'
window.dispatchEvent(new CustomEvent('user-login', { detail: data.user }))
setTimeout(() => {
window.location.href = '/'
}, 1000)
}
} catch (err) {
error.value = '网络错误,请稍后重试'
console.error(err)
} finally {
loading.value = false
}
}
function handleGithubLogin() {
error.value = 'GitHub 登录功能即将上线'
}
</script>
<style scoped>
.login-container {
display: flex;
justify-content: center;
align-items: center;
min-height: 60vh;
padding: 2rem;
}
.login-card {
background: var(--card-bg, #fff);
border-radius: 12px;
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
padding: 2rem;
width: 100%;
max-width: 400px;
}
.tabs {
display: flex;
margin-bottom: 1.5rem;
border-bottom: 2px solid var(--border-color, #e5e7eb);
}
.tab {
flex: 1;
padding: 0.75rem 1rem;
border: none;
background: none;
cursor: pointer;
font-size: 1rem;
color: var(--text-muted, #6b7280);
transition: all 0.3s;
}
.tab.active {
color: var(--primary, #3b82f6);
border-bottom: 2px solid var(--primary, #3b82f6);
margin-bottom: -2px;
}
.form-group {
margin-bottom: 1rem;
}
.form-group label {
display: block;
margin-bottom: 0.5rem;
font-size: 0.875rem;
font-weight: 500;
color: var(--text, #374151);
}
.form-group input {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid var(--border-color, #d1d5db);
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.2s;
}
.form-group input:focus {
outline: none;
border-color: var(--primary, #3b82f6);
box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}
.error-message {
color: #ef4444;
font-size: 0.875rem;
margin-bottom: 1rem;
padding: 0.5rem;
background: #fef2f2;
border-radius: 6px;
}
.success-message {
color: #22c55e;
font-size: 0.875rem;
margin-bottom: 1rem;
padding: 0.5rem;
background: #f0fdf4;
border-radius: 6px;
}
.submit-btn {
width: 100%;
padding: 0.875rem;
background: var(--primary, #3b82f6);
color: white;
border: none;
border-radius: 8px;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: background 0.3s;
}
.submit-btn:hover:not(:disabled) {
background: var(--primary-hover, #2563eb);
}
.submit-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.divider {
display: flex;
align-items: center;
margin: 1.5rem 0;
}
.divider::before,
.divider::after {
content: '';
flex: 1;
height: 1px;
background: var(--border-color, #e5e7eb);
}
.divider span {
padding: 0 1rem;
color: var(--text-muted, #9ca3af);
font-size: 0.875rem;
}
.github-btn {
width: 100%;
display: flex;
align-items: center;
justify-content: center;
gap: 0.5rem;
padding: 0.875rem;
background: #24292e;
color: white;
border: none;
border-radius: 8px;
font-size: 1rem;
cursor: pointer;
transition: background 0.3s;
}
.github-btn:hover {
background: #1a1e22;
}
</style>

View File

@@ -0,0 +1,67 @@
---
/**
* TypstBlock 组件
*
* 用于在 MDX 文章中渲染 Typst 数学公式和复杂排版。
*
* 使用方式:
* <TypstBlock>
* $ integral_0^infinity e^(-x^2) dif x = sqrt(pi) / 2 $
* </TypstBlock>
*
* 注意:此组件需要在构建时安装 Typst 编译器。
* 如果 Typst 未安装,会显示原始代码块作为降级方案。
*/
interface Props {
class?: string;
}
const { class: className = '' } = Astro.props;
// 获取子内容Typst 代码)
const content = await Astro.slots.render('default');
const typstCode = content?.trim() || '';
---
<div class:list={['typst-block', 'my-6', className]}>
{/*
Typst 渲染区域
在实际实现中,这里会调用 Typst 编译器将代码渲染为 SVG
目前作为占位符显示
*/}
<div class="p-4 bg-muted rounded-lg border border-border overflow-x-auto">
{typstCode ? (
<div class="flex flex-col items-center">
{/* SVG 输出区域 (构建时会被替换为实际的 Typst 渲染结果) */}
<div class="typst-output text-lg" data-typst-code={typstCode}>
<code class="font-mono text-primary-600 dark:text-primary-400">
{typstCode}
</code>
</div>
<span class="text-xs text-foreground/40 mt-2">Typst 公式</span>
</div>
) : (
<p class="text-foreground/40 text-center">请提供 Typst 代码</p>
)}
</div>
</div>
<style>
.typst-block {
/* 确保 Typst 内容居中显示 */
text-align: center;
}
.typst-output {
/* 为数学公式提供合适的样式 */
font-family: 'Latin Modern Math', 'STIX Two Math', 'Noto Serif SC', serif;
line-height: 1.8;
}
.typst-output svg {
/* SVG 输出样式 */
max-width: 100%;
height: auto;
}
</style>

View File

@@ -0,0 +1,88 @@
---
title: 'NovaBlog 入门指南'
description: '这是一篇介绍 NovaBlog 博客系统核心功能的示例文章,展示 MDX 动态组件支持。'
pubDate: 2026-02-28
author: 'NovaBlog Team'
category: '教程'
tags: ['入门', 'MDX', 'Astro']
heroImage: '/images/hello-world.jpg'
---
# 欢迎来到 NovaBlog
NovaBlog 是一个极简、高效的程序员博客系统,采用 **静态渲染 + 轻量级微服务** 架构。
## 核心特性
### 🚀 极致性能
基于 Astro 的 Islands Architecture群岛架构大部分页面为 Zero-JS仅在需要交互的地方加载 JavaScript。
### ✍️ MDX 支持
在 Markdown 中直接嵌入交互组件:
```jsx
<Counter client:visible />
```
上面的组件会在可见时自动加载并挂载 JavaScript。
### 📐 Typst 学术排版
支持复杂的数学公式渲染:
<TypstBlock>
$ integral_0^infinity e^(-x^2) dif x = sqrt(pi) / 2 $
</TypstBlock>
## 代码高亮
支持多种编程语言的语法高亮:
```typescript
// TypeScript 示例
interface Post {
title: string;
content: string;
tags: string[];
}
async function getPosts(): Promise<Post[]> {
return await fetch('/api/posts').then(res => res.json());
}
```
```go
// Go 示例
package main
import "fmt"
func main() {
fmt.Println("Hello, NovaBlog!")
}
```
## 表格支持
| 特性 | 描述 |
|------|------|
| 静态渲染 | 构建时生成 HTML极速加载 |
| MDX 支持 | 在 Markdown 中嵌入组件 |
| 低资源 | 2C1G 即可运行 |
| Docker | 一键容器化部署 |
## 引用
> 优秀的博客系统应该让作者专注于内容,而非配置。
>
> — NovaBlog 设计理念
## 下一步
1. 在 `src/content/blog/` 目录下创建新的 `.md` 或 `.mdx` 文件
2. 配置 Frontmatter 元数据
3. 运行 `npm run dev` 预览效果
开始你的写作之旅吧! 🎉

40
src/content/config.ts Normal file
View File

@@ -0,0 +1,40 @@
import { defineCollection, z } from 'astro:content';
// 博客文章集合
const blogCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string().optional(),
pubDate: z.coerce.date(),
updatedDate: z.coerce.date().optional(),
heroImage: z.string().optional(),
heroAlt: z.string().optional(),
tags: z.array(z.string()).default([]),
category: z.string().optional(),
draft: z.boolean().default(false),
author: z.string().default('Anonymous'),
featured: z.boolean().default(false),
// 用于评论区
comments: z.boolean().default(true),
// 文章唯一标识符,用于评论关联
slug: z.string().optional(),
}),
});
// 页面集合 (如关于页面等)
const pagesCollection = defineCollection({
type: 'content',
schema: z.object({
title: z.string(),
description: z.string().optional(),
layout: z.string().optional(),
showInNav: z.boolean().default(false),
order: z.number().default(0),
}),
});
export const collections = {
blog: blogCollection,
pages: pagesCollection,
};

15
src/env.d.ts vendored Normal file
View File

@@ -0,0 +1,15 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
// Vue 组件类型声明
declare module '*.vue' {
import type { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
// MDX 文件类型声明
declare module '*.mdx' {
import type { MDXComponent } from 'mdx/types';
export default MDXComponent;
}

View File

@@ -0,0 +1,224 @@
---
import '../styles/global.css';
interface Props {
title: string;
description?: string;
image?: string;
canonicalURL?: string;
}
const {
title,
description = 'NovaBlog - 一个极简、高效的程序员博客系统',
image = '/og-default.png',
canonicalURL = Astro.url.href,
} = Astro.props;
const { site } = Astro;
const socialImageURL = image.startsWith('http') ? image : new URL(image, site).href;
---
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="generator" content={Astro.generator} />
<!-- SEO Meta Tags -->
<title>{title}</title>
<meta name="description" content={description} />
<link rel="canonical" href={canonicalURL} />
<!-- Open Graph -->
<meta property="og:type" content="website" />
<meta property="og:url" content={canonicalURL} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={socialImageURL} />
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={socialImageURL} />
<!-- Favicon -->
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<link rel="icon" type="image/x-icon" href="/favicon.ico" />
<!-- Preload Fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&family=Noto+Serif+SC:wght@400;600&display=swap"
rel="stylesheet"
/>
<!-- Dark Mode Script (防止闪烁) -->
<script is:inline>
const theme = (() => {
if (typeof localStorage !== 'undefined' && localStorage.getItem('theme')) {
return localStorage.getItem('theme');
}
if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
return 'dark';
}
return 'light';
})();
if (theme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
</script>
</head>
<body class="min-h-screen flex flex-col bg-background text-foreground">
<!-- Header -->
<header class="sticky top-0 z-50 glass border-b border-border">
<nav class="content-width h-16 flex items-center justify-between">
<!-- Logo -->
<a href="/" class="flex items-center gap-2 text-xl font-bold hover:text-primary-500 transition-colors">
<svg class="w-8 h-8" viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="32" height="32" rx="8" fill="url(#logo-gradient)" />
<path
d="M8 12L16 8L24 12V20L16 24L8 20V12Z"
stroke="white"
stroke-width="2"
stroke-linejoin="round"
/>
<circle cx="16" cy="16" r="3" fill="white" />
<defs>
<linearGradient id="logo-gradient" x1="0" y1="0" x2="32" y2="32" gradientUnits="userSpaceOnUse">
<stop stop-color="#0ea5e9" />
<stop offset="1" stop-color="#8b5cf6" />
</linearGradient>
</defs>
</svg>
<span class="gradient-text">NovaBlog</span>
</a>
<!-- Navigation Links -->
<div class="hidden md:flex items-center gap-6">
<a href="/" class="text-foreground/70 hover:text-foreground transition-colors">首页</a>
<a href="/blog" class="text-foreground/70 hover:text-foreground transition-colors">博客</a>
<a href="/tags" class="text-foreground/70 hover:text-foreground transition-colors">标签</a>
<a href="/about" class="text-foreground/70 hover:text-foreground transition-colors">关于</a>
</div>
<!-- Actions -->
<div class="flex items-center gap-3">
<!-- Login Link -->
<a href="/login" class="btn-ghost px-3 py-1.5 rounded-lg text-sm font-medium">
登录
</a>
<!-- Theme Toggle -->
<button
id="theme-toggle"
class="btn-ghost p-2 rounded-lg"
aria-label="切换主题"
>
<svg class="w-5 h-5 hidden dark:block" fill="currentColor" viewBox="0 0 20 20">
<path
d="M10 2a1 1 0 011 1v1a1 1 0 11-2 0V3a1 1 0 011-1zm4 8a4 4 0 11-8 0 4 4 0 018 0zm-.464 4.95l.707.707a1 1 0 001.414-1.414l-.707-.707a1 1 0 00-1.414 1.414zm2.12-10.607a1 1 0 010 1.414l-.706.707a1 1 0 11-1.414-1.414l.707-.707a1 1 0 011.414 0zM17 11a1 1 0 100-2h-1a1 1 0 100 2h1zm-7 4a1 1 0 011 1v1a1 1 0 11-2 0v-1a1 1 0 011-1zM5.05 6.464A1 1 0 106.465 5.05l-.708-.707a1 1 0 00-1.414 1.414l.707.707zm1.414 8.486l-.707.707a1 1 0 01-1.414-1.414l.707-.707a1 1 0 011.414 1.414zM4 11a1 1 0 100-2H3a1 1 0 000 2h1z"
/>
</svg>
<svg class="w-5 h-5 block dark:hidden" fill="currentColor" viewBox="0 0 20 20">
<path
d="M17.293 13.293A8 8 0 016.707 2.707a8.001 8.001 0 1010.586 10.586z"
/>
</svg>
</button>
<!-- Mobile Menu Toggle -->
<button
id="mobile-menu-toggle"
class="btn-ghost p-2 rounded-lg md:hidden"
aria-label="打开菜单"
>
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
</div>
</nav>
<!-- Mobile Menu -->
<div id="mobile-menu" class="hidden md:hidden border-t border-border">
<div class="content-width py-4 flex flex-col gap-3">
<a href="/" class="text-foreground/70 hover:text-foreground transition-colors py-2">首页</a>
<a href="/blog" class="text-foreground/70 hover:text-foreground transition-colors py-2">博客</a>
<a href="/tags" class="text-foreground/70 hover:text-foreground transition-colors py-2">标签</a>
<a href="/about" class="text-foreground/70 hover:text-foreground transition-colors py-2">关于</a>
</div>
</div>
</header>
<!-- Main Content -->
<main class="flex-1">
<slot />
</main>
<!-- Footer -->
<footer class="border-t border-border bg-muted/30">
<div class="content-width py-12">
<div class="grid grid-cols-1 md:grid-cols-3 gap-8">
<!-- About -->
<div>
<h3 class="font-semibold text-lg mb-4">NovaBlog</h3>
<p class="text-foreground/60 text-sm leading-relaxed">
一个极简、高效的程序员博客系统。支持 MDX、Typst 学术排版,静态渲染 + 轻量级微服务架构。
</p>
</div>
<!-- Links -->
<div>
<h3 class="font-semibold text-lg mb-4">快速链接</h3>
<ul class="space-y-2 text-sm">
<li><a href="/blog" class="text-foreground/60 hover:text-primary-500 transition-colors">全部文章</a></li>
<li><a href="/tags" class="text-foreground/60 hover:text-primary-500 transition-colors">标签分类</a></li>
<li><a href="/about" class="text-foreground/60 hover:text-primary-500 transition-colors">关于我</a></li>
<li><a href="/rss.xml" class="text-foreground/60 hover:text-primary-500 transition-colors">RSS 订阅</a></li>
</ul>
</div>
<!-- Tech Stack -->
<div>
<h3 class="font-semibold text-lg mb-4">技术栈</h3>
<ul class="space-y-2 text-sm text-foreground/60">
<li>前端: Astro + Vue 3 + Tailwind CSS</li>
<li>后端: Go + Gin + SQLite</li>
<li>部署: Docker + Nginx</li>
</ul>
</div>
</div>
<!-- Copyright -->
<div class="mt-8 pt-8 border-t border-border text-center text-sm text-foreground/40">
<p>&copy; {new Date().getFullYear()} NovaBlog. All rights reserved.</p>
</div>
</div>
</footer>
<!-- Theme Toggle Script -->
<script>
const themeToggle = document.getElementById('theme-toggle');
const mobileMenuToggle = document.getElementById('mobile-menu-toggle');
const mobileMenu = document.getElementById('mobile-menu');
// Theme toggle
themeToggle?.addEventListener('click', () => {
const isDark = document.documentElement.classList.toggle('dark');
localStorage.setItem('theme', isDark ? 'dark' : 'light');
});
// Mobile menu toggle
mobileMenuToggle?.addEventListener('click', () => {
mobileMenu?.classList.toggle('hidden');
});
</script>
</body>
</html>

View File

@@ -0,0 +1,128 @@
---
import BaseLayout from './BaseLayout.astro';
import CommentSection from '../components/CommentSection.vue';
import LikeButton from '../components/LikeButton.vue';
import type { CollectionEntry } from 'astro:content';
interface Props {
post: CollectionEntry<'blog'>;
}
const { post } = Astro.props;
const { title, description, pubDate, updatedDate, heroImage, heroAlt, tags, author, category } = post.data;
// 格式化日期
const formatDate = (date: Date) => {
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
};
// 计算阅读时间(估算)
const readingTime = Math.ceil(post.body?.split(/\s+/).length / 400) || 1;
---
<BaseLayout title={title} description={description} image={heroImage}>
<article class="py-12">
<!-- 文章头部 -->
<header class="content-width mb-12">
<!-- 分类和标签 -->
<div class="flex flex-wrap items-center gap-3 mb-4">
{category && (
<span class="tag bg-primary-500 text-white">
{category}
</span>
)}
{tags && tags.map((tag: string) => (
<span class="tag">
#{tag}
</span>
))}
</div>
<!-- 标题 -->
<h1 class="text-3xl md:text-4xl lg:text-5xl font-bold mb-6 leading-tight">
{title}
</h1>
<!-- 元信息 -->
<div class="article-meta flex-wrap">
<span class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
{author}
</span>
<span class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
发布于 {formatDate(pubDate)}
</span>
{updatedDate && (
<span class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
</svg>
更新于 {formatDate(updatedDate)}
</span>
)}
<span class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
</svg>
预计阅读 {readingTime} 分钟
</span>
</div>
<!-- 封面图 -->
{heroImage && (
<div class="mt-8 rounded-xl overflow-hidden">
<img
src={heroImage}
alt={heroAlt || title}
class="w-full aspect-video object-cover"
loading="eager"
/>
</div>
)}
</header>
<!-- 文章内容 -->
<div class="content-width">
<div class="max-w-3xl mx-auto">
<div class="prose-container prose-headings:font-semibold prose-headings:tracking-tight prose-h1:text-3xl prose-h2:text-2xl prose-h3:text-xl prose-p:leading-relaxed prose-a:text-primary-500 prose-a:no-underline hover:prose-a:underline prose-img:rounded-xl prose-code:text-primary-400">
<slot />
</div>
</div>
</div>
<!-- 文章底部 -->
<footer class="content-width mt-12">
<div class="max-w-3xl mx-auto">
<!-- 点赞按钮 -->
<div class="flex justify-center py-6">
<LikeButton postId={post.id} client:visible />
</div>
<!-- 分割线 -->
<hr class="border-border my-8" />
<!-- 文章导航 -->
<div class="flex justify-between items-center gap-4 py-6">
<a href="/blog" class="btn-secondary">
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
返回文章列表
</a>
</div>
<!-- 评论区 -->
<CommentSection postId={post.id} client:visible />
</div>
</footer>
</article>
</BaseLayout>

20
src/mdx-components.ts Normal file
View File

@@ -0,0 +1,20 @@
import Counter from './components/Counter.vue';
import TypstBlock from './components/TypstBlock.astro';
/**
* MDX 组件映射
*
* 在 MDX 文件中可以直接使用这些组件,无需 import。
* 例如:
* ```mdx
* <Counter client:visible />
* <TypstBlock>$ E = mc^2 $</TypstBlock>
* ```
*/
export const components = {
// Vue 交互组件
Counter,
// Astro 静态组件
TypstBlock,
};

View File

@@ -0,0 +1,32 @@
---
import { getCollection, type CollectionEntry } from 'astro:content';
import PostLayout from '../../layouts/PostLayout.astro';
import Counter from '../../components/Counter.vue';
import TypstBlock from '../../components/TypstBlock.astro';
// MDX 组件映射
const mdxComponents = {
Counter,
TypstBlock,
};
// 生成所有文章的静态路径
export async function getStaticPaths() {
const posts = await getCollection('blog');
return posts.map((post) => ({
params: { slug: post.slug || post.id },
props: { post },
}));
}
interface Props {
post: CollectionEntry<'blog'>;
}
const { post } = Astro.props;
const { Content } = await post.render();
---
<PostLayout post={post}>
<Content components={mdxComponents} />
</PostLayout>

120
src/pages/blog/index.astro Normal file
View File

@@ -0,0 +1,120 @@
---
import BaseLayout from '../../layouts/BaseLayout.astro';
import { getCollection } from 'astro:content';
// 获取所有非草稿文章
const allPosts = await getCollection('blog', ({ data }) => {
return !data.draft;
});
// 按日期排序
const sortedPosts = allPosts.sort((a, b) =>
b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
);
// 格式化日期
const formatDate = (date: Date) => {
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
};
---
<BaseLayout title="博客文章 - NovaBlog">
<div class="py-12">
<div class="content-width">
<!-- Page Header -->
<div class="text-center mb-12">
<h1 class="text-3xl md:text-4xl font-bold mb-4">博客文章</h1>
<p class="text-foreground/60">探索技术,记录成长</p>
</div>
{sortedPosts.length > 0 ? (
<div class="max-w-4xl mx-auto space-y-8">
{sortedPosts.map((post) => (
<article class="card group">
<a href={`/blog/${post.slug || post.id}`} class="block">
<div class="flex flex-col md:flex-row gap-6">
<!-- 封面图 -->
{post.data.heroImage ? (
<div class="md:w-48 flex-shrink-0">
<div class="aspect-video md:aspect-square rounded-lg overflow-hidden">
<img
src={post.data.heroImage}
alt={post.data.heroAlt || post.data.title}
class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
loading="lazy"
/>
</div>
</div>
) : (
<div class="md:w-48 flex-shrink-0 hidden md:block">
<div class="aspect-square rounded-lg bg-gradient-to-br from-primary-100 to-accent/20 dark:from-primary-900 dark:to-accent/10 flex items-center justify-center">
<svg class="w-12 h-12 text-primary-300 dark:text-primary-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
</div>
)}
<!-- 内容 -->
<div class="flex-1 min-w-0">
<!-- 标签 -->
<div class="flex flex-wrap items-center gap-2 mb-2">
{post.data.category && (
<span class="tag text-xs bg-primary-500 text-white">
{post.data.category}
</span>
)}
{(post.data.tags || []).slice(0, 3).map((tag: string) => (
<span class="tag text-xs">#{tag}</span>
))}
</div>
<!-- 标题 -->
<h2 class="text-xl font-semibold mb-2 group-hover:text-primary-500 transition-colors">
{post.data.title}
</h2>
<!-- 描述 -->
{post.data.description && (
<p class="text-foreground/60 text-sm mb-4 line-clamp-2">
{post.data.description}
</p>
)}
<!-- 元信息 -->
<div class="flex items-center gap-4 text-xs text-foreground/40">
<span class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
{formatDate(post.data.pubDate)}
</span>
<span class="flex items-center gap-1">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
</svg>
{post.data.author}
</span>
</div>
</div>
</div>
</a>
</article>
))}
</div>
) : (
<div class="text-center py-16 text-foreground/40">
<svg class="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<p class="mb-2">暂无文章</p>
<p class="text-sm">请在 src/content/blog/ 目录下添加 Markdown 文件</p>
</div>
)}
</div>
</div>
</BaseLayout>

197
src/pages/index.astro Normal file
View File

@@ -0,0 +1,197 @@
---
import BaseLayout from '../layouts/BaseLayout.astro';
import { getCollection } from 'astro:content';
// 获取最新的博客文章
const allPosts = await getCollection('blog', ({ data }) => {
return !data.draft;
});
// 按日期排序
const sortedPosts = allPosts.sort((a, b) =>
b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
);
// 获取前6篇作为精选
const featuredPosts = sortedPosts.slice(0, 6);
// 获取所有标签
const allTags = [...new Set(allPosts.flatMap(post => post.data.tags || []))];
// 格式化日期
const formatDate = (date: Date) => {
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
};
---
<BaseLayout title="NovaBlog - 极简程序员博客">
<!-- Hero Section -->
<section class="py-20 md:py-32 bg-gradient-to-br from-primary-50 via-background to-accent/10 dark:from-primary-900/20 dark:to-accent/5">
<div class="content-width text-center">
<h1 class="text-4xl md:text-5xl lg:text-6xl font-bold mb-6">
<span class="gradient-text">NovaBlog</span>
</h1>
<p class="text-xl md:text-2xl text-foreground/60 max-w-2xl mx-auto mb-8">
一个极简、高效的程序员博客系统
</p>
<p class="text-foreground/50 max-w-xl mx-auto mb-10">
支持 MDX 动态组件、Typst 学术排版,静态渲染 + 轻量级微服务架构,极致性能与优雅排版的完美结合
</p>
<div class="flex flex-wrap justify-center gap-4">
<a href="/blog" class="btn-primary">
浏览文章
<svg class="w-4 h-4 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3" />
</svg>
</a>
<a href="/about" class="btn-secondary">
了解更多
</a>
</div>
</div>
</section>
<!-- Featured Posts -->
<section class="py-16">
<div class="content-width">
<div class="flex items-center justify-between mb-8">
<h2 class="text-2xl md:text-3xl font-bold">最新文章</h2>
<a href="/blog" class="text-primary-500 hover:text-primary-600 transition-colors flex items-center gap-1">
查看全部
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</a>
</div>
{featuredPosts.length > 0 ? (
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{featuredPosts.map((post) => (
<article class="card group cursor-pointer">
<a href={`/blog/${post.slug || post.id}`}>
{/* 封面图 */}
{post.data.heroImage ? (
<div class="aspect-video rounded-lg overflow-hidden mb-4 -mt-6 -mx-6 w-[calc(100%+3rem)]">
<img
src={post.data.heroImage}
alt={post.data.heroAlt || post.data.title}
class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
loading="lazy"
/>
</div>
) : (
<div class="aspect-video rounded-lg bg-gradient-to-br from-primary-100 to-accent/20 dark:from-primary-900 dark:to-accent/10 mb-4 -mt-6 -mx-6 w-[calc(100%+3rem)] flex items-center justify-center">
<svg class="w-12 h-12 text-primary-300 dark:text-primary-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
</div>
)}
<!-- 分类 -->
{post.data.category && (
<span class="tag text-xs mb-3">
{post.data.category}
</span>
)}
<!-- 标题 -->
<h3 class="text-lg font-semibold mb-2 group-hover:text-primary-500 transition-colors line-clamp-2">
{post.data.title}
</h3>
<!-- 描述 -->
{post.data.description && (
<p class="text-foreground/60 text-sm mb-4 line-clamp-2">
{post.data.description}
</p>
)}
<!-- 元信息 -->
<div class="flex items-center justify-between text-xs text-foreground/40">
<span>{formatDate(post.data.pubDate)}</span>
<span>{post.data.author}</span>
</div>
</a>
</article>
))}
</div>
) : (
<div class="text-center py-16 text-foreground/40">
<svg class="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
<p>暂无文章,请在 src/content/blog/ 目录下添加 Markdown 文件</p>
</div>
)}
</div>
</section>
<!-- Tags Section -->
<section class="py-16 bg-muted/30">
<div class="content-width">
<h2 class="text-2xl md:text-3xl font-bold mb-8 text-center">标签云</h2>
{allTags.length > 0 ? (
<div class="flex flex-wrap justify-center gap-3">
{allTags.map((tag: string) => (
<a href={`/tags/${tag}`} class="tag hover:bg-primary-200 dark:hover:bg-primary-800 transition-colors">
#{tag}
</a>
))}
</div>
) : (
<p class="text-center text-foreground/40">暂无标签</p>
)}
</div>
</section>
<!-- Features Section -->
<section class="py-16">
<div class="content-width">
<h2 class="text-2xl md:text-3xl font-bold mb-12 text-center">核心特性</h2>
<div class="grid grid-cols-1 md:grid-cols-3 gap-8">
<!-- Feature 1 -->
<div class="text-center">
<div class="w-16 h-16 mx-auto mb-4 rounded-2xl bg-primary-100 dark:bg-primary-900 flex items-center justify-center">
<svg class="w-8 h-8 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
</div>
<h3 class="text-lg font-semibold mb-2">极致性能</h3>
<p class="text-foreground/60 text-sm">
静态渲染 + Islands 架构Zero-JS 默认,极致的加载速度
</p>
</div>
<!-- Feature 2 -->
<div class="text-center">
<div class="w-16 h-16 mx-auto mb-4 rounded-2xl bg-primary-100 dark:bg-primary-900 flex items-center justify-center">
<svg class="w-8 h-8 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
</svg>
</div>
<h3 class="text-lg font-semibold mb-2">MDX 支持</h3>
<p class="text-foreground/60 text-sm">
在 Markdown 中嵌入 Vue/React 组件,实现丰富的交互效果
</p>
</div>
<!-- Feature 3 -->
<div class="text-center">
<div class="w-16 h-16 mx-auto mb-4 rounded-2xl bg-primary-100 dark:bg-primary-900 flex items-center justify-center">
<svg class="w-8 h-8 text-primary-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
</svg>
</div>
<h3 class="text-lg font-semibold mb-2">低资源占用</h3>
<p class="text-foreground/60 text-sm">
Go 后端 + SQLite2C1G 小鸡也能流畅运行
</p>
</div>
</div>
</div>
</section>
</BaseLayout>

36
src/pages/login.astro Normal file
View File

@@ -0,0 +1,36 @@
---
import BaseLayout from '../layouts/BaseLayout.astro';
import LoginForm from '../components/LoginForm.vue';
---
<BaseLayout title="登录 - NovaBlog">
<main class="login-page">
<h1 class="page-title">欢迎回来</h1>
<p class="page-subtitle">登录您的账户以发表评论和管理内容</p>
<LoginForm client:visible />
</main>
</BaseLayout>
<style>
.login-page {
max-width: 1200px;
margin: 0 auto;
padding: 2rem 1rem;
}
.page-title {
text-align: center;
font-size: 2rem;
font-weight: 700;
margin-bottom: 0.5rem;
color: var(--text);
}
.page-subtitle {
text-align: center;
color: var(--text-muted);
margin-bottom: 2rem;
}
</style>
</task_progress>
</write_to_file>

102
src/pages/tags/[tag].astro Normal file
View File

@@ -0,0 +1,102 @@
---
import BaseLayout from '../../layouts/BaseLayout.astro';
import { getCollection } from 'astro:content';
// 生成所有标签的静态路径
export async function getStaticPaths() {
const posts = await getCollection('blog');
const allTags = [...new Set(posts.flatMap((post) => post.data.tags || []))];
return allTags.map((tag) => ({
params: { tag },
}));
}
// 获取当前标签
const { tag } = Astro.params;
// 获取该标签下的所有文章
const allPosts = await getCollection('blog', ({ data }) => {
return !data.draft && (data.tags || []).includes(tag || '');
});
// 按日期排序
const sortedPosts = allPosts.sort((a, b) =>
b.data.pubDate.valueOf() - a.data.pubDate.valueOf()
);
// 格式化日期
const formatDate = (date: Date) => {
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
};
---
<BaseLayout title={`#${tag} - NovaBlog`}>
<div class="py-12">
<div class="content-width">
<div class="text-center mb-12">
<h1 class="text-3xl md:text-4xl font-bold mb-4">
<span class="gradient-text">#{tag}</span>
</h1>
<p class="text-foreground/60">{sortedPosts.length} 篇文章</p>
</div>
<div class="max-w-4xl mx-auto space-y-8">
{sortedPosts.map((post) => (
<article class="card group">
<a href={`/blog/${post.slug || post.id}`} class="block">
<div class="flex flex-col md:flex-row gap-6">
<!-- 封面图 -->
{post.data.heroImage ? (
<div class="md:w-48 flex-shrink-0">
<div class="aspect-video md:aspect-square rounded-lg overflow-hidden">
<img
src={post.data.heroImage}
alt={post.data.heroAlt || post.data.title}
class="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
loading="lazy"
/>
</div>
</div>
) : null}
<!-- 内容 -->
<div class="flex-1 min-w-0">
<!-- 标题 -->
<h2 class="text-xl font-semibold mb-2 group-hover:text-primary-500 transition-colors">
{post.data.title}
</h2>
<!-- 描述 -->
{post.data.description && (
<p class="text-foreground/60 text-sm mb-4 line-clamp-2">
{post.data.description}
</p>
)}
<!-- 元信息 -->
<div class="flex items-center gap-4 text-xs text-foreground/40">
<span>{formatDate(post.data.pubDate)}</span>
<span>{post.data.author}</span>
</div>
</div>
</div>
</a>
</article>
))}
</div>
<div class="text-center mt-12">
<a href="/tags" class="btn-secondary">
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
返回标签列表
</a>
</div>
</div>
</div>
</BaseLayout>

View File

@@ -0,0 +1,54 @@
---
import BaseLayout from '../../layouts/BaseLayout.astro';
import { getCollection } from 'astro:content';
// 获取所有文章
const allPosts = await getCollection('blog', ({ data }) => {
return !data.draft;
});
// 统计标签
const tagMap = new Map<string, number>();
allPosts.forEach((post) => {
(post.data.tags || []).forEach((tag: string) => {
tagMap.set(tag, (tagMap.get(tag) || 0) + 1);
});
});
// 按文章数量排序
const sortedTags = [...tagMap.entries()].sort((a, b) => b[1] - a[1]);
---
<BaseLayout title="标签 - NovaBlog">
<div class="py-12">
<div class="content-width">
<div class="text-center mb-12">
<h1 class="text-3xl md:text-4xl font-bold mb-4">标签</h1>
<p class="text-foreground/60">按标签浏览文章</p>
</div>
{sortedTags.length > 0 ? (
<div class="max-w-2xl mx-auto">
<div class="flex flex-wrap justify-center gap-4">
{sortedTags.map(([tag, count]) => (
<a
href={`/tags/${tag}`}
class="card px-6 py-4 flex items-center gap-3 hover:border-primary-500 transition-colors"
>
<span class="text-lg font-medium">#{tag}</span>
<span class="text-sm text-foreground/40">{count} 篇文章</span>
</a>
))}
</div>
</div>
) : (
<div class="text-center py-16 text-foreground/40">
<svg class="w-16 h-16 mx-auto mb-4 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z" />
</svg>
<p>暂无标签</p>
</div>
)}
</div>
</div>
</BaseLayout>

207
src/styles/global.css Normal file
View File

@@ -0,0 +1,207 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* ========================================
CSS 变量主题系统
======================================== */
:root {
/* 主色调 */
--primary-50: #f0f9ff;
--primary-100: #e0f2fe;
--primary-200: #bae6fd;
--primary-300: #7dd3fc;
--primary-400: #38bdf8;
--primary-500: #0ea5e9;
--primary-600: #0284c7;
--primary-700: #0369a1;
--primary-800: #075985;
--primary-900: #0c4a6e;
/* 背景色与前景色 */
--color-background: #ffffff;
--color-foreground: #1e293b;
--color-muted: #f1f5f9;
--color-accent: #8b5cf6;
--color-border: #e2e8f0;
--color-code-bg: #1e293b;
/* 字体 */
--font-sans: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
--font-mono: 'JetBrains Mono', 'Fira Code', Consolas, Monaco, 'Andale Mono', monospace;
--font-serif: 'Noto Serif SC', Georgia, 'Times New Roman', serif;
/* 间距 */
--header-height: 4rem;
--content-max-width: 80rem;
}
/* 暗黑模式 */
.dark {
--color-background: #0f172a;
--color-foreground: #f1f5f9;
--color-muted: #1e293b;
--color-accent: #a78bfa;
--color-border: #334155;
--color-code-bg: #0f172a;
}
/* ========================================
基础样式
======================================== */
@layer base {
html {
scroll-behavior: smooth;
}
body {
@apply bg-background text-foreground antialiased;
font-family: var(--font-sans);
}
/* 选中文本样式 */
::selection {
@apply bg-primary-200 text-primary-900;
}
.dark ::selection {
@apply bg-primary-700 text-primary-100;
}
/* 链接基础样式 */
a {
@apply transition-colors duration-200;
}
/* 代码块样式 */
code {
@apply font-mono text-sm;
}
pre {
@apply overflow-x-auto rounded-lg p-4;
}
/* 滚动条样式 */
::-webkit-scrollbar {
@apply w-2 h-2;
}
::-webkit-scrollbar-track {
@apply bg-muted;
}
::-webkit-scrollbar-thumb {
@apply bg-primary-400 rounded-full;
}
::-webkit-scrollbar-thumb:hover {
@apply bg-primary-500;
}
}
/* ========================================
组件样式
======================================== */
@layer components {
/* 文章内容容器 */
.prose-container {
@apply max-w-none prose prose-lg dark:prose-invert;
}
/* 卡片样式 */
.card {
@apply bg-background border border-border rounded-xl p-6 shadow-sm hover:shadow-md transition-shadow duration-200;
}
/* 按钮样式 */
.btn {
@apply inline-flex items-center justify-center px-4 py-2 rounded-lg font-medium transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2;
}
.btn-primary {
@apply btn bg-primary-500 text-white hover:bg-primary-600 focus:ring-primary-500;
}
.btn-secondary {
@apply btn bg-muted text-foreground hover:bg-primary-100 dark:hover:bg-primary-900 focus:ring-primary-500;
}
.btn-ghost {
@apply btn bg-transparent hover:bg-muted focus:ring-primary-500;
}
/* 输入框样式 */
.input {
@apply w-full px-4 py-2 bg-background border border-border rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent transition-colors duration-200;
}
/* 文章元信息样式 */
.article-meta {
@apply flex items-center gap-4 text-sm;
color: rgba(30, 41, 59, 0.6);
}
.dark .article-meta {
color: rgba(241, 245, 249, 0.6);
}
/* 标签样式 */
.tag {
@apply inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-primary-100 text-primary-700 dark:bg-primary-900 dark:text-primary-300;
}
/* 渐变文本 */
.gradient-text {
@apply bg-clip-text text-transparent bg-gradient-to-r from-primary-500 to-purple-500;
}
}
/* ========================================
工具类
======================================== */
@layer utilities {
/* 文章内容最大宽度 */
.content-width {
max-width: var(--content-max-width);
@apply mx-auto px-4 sm:px-6 lg:px-8;
}
/* 隐藏滚动条但保持滚动功能 */
.hide-scrollbar {
-ms-overflow-style: none;
scrollbar-width: none;
}
.hide-scrollbar::-webkit-scrollbar {
display: none;
}
/* 玻璃效果 */
.glass {
@apply backdrop-blur-md;
background-color: rgba(255, 255, 255, 0.8);
}
.dark .glass {
background-color: rgba(15, 23, 42, 0.8);
}
/* 渐变边框 */
.gradient-border {
position: relative;
}
.gradient-border::before {
content: '';
position: absolute;
inset: 0;
padding: 1px;
border-radius: inherit;
background: linear-gradient(135deg, var(--primary-500), var(--color-accent));
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
pointer-events: none;
}
}

88
tailwind.config.mjs Normal file
View File

@@ -0,0 +1,88 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
darkMode: 'class',
theme: {
extend: {
colors: {
// 主题色
primary: {
50: '#f0f9ff',
100: '#e0f2fe',
200: '#bae6fd',
300: '#7dd3fc',
400: '#38bdf8',
500: '#0ea5e9',
600: '#0284c7',
700: '#0369a1',
800: '#075985',
900: '#0c4a6e',
950: '#082f49',
},
// 背景色
background: 'var(--color-background)',
'background-alt': 'var(--color-background-alt)',
// 前景色
foreground: 'var(--color-foreground)',
'foreground-alt': 'var(--color-foreground-alt)',
// 边框色
border: 'var(--color-border)',
// 静音色
muted: 'var(--color-muted)',
},
fontFamily: {
sans: ['Inter', 'system-ui', 'sans-serif'],
mono: ['JetBrains Mono', 'Menlo', 'monospace'],
},
typography: {
DEFAULT: {
css: {
maxWidth: '65ch',
color: 'var(--color-foreground)',
a: {
color: 'var(--color-primary-500)',
'&:hover': {
color: 'var(--color-primary-600)',
},
},
code: {
color: 'var(--color-primary-500)',
backgroundColor: 'var(--color-muted)',
padding: '0.25rem 0.375rem',
borderRadius: '0.25rem',
fontWeight: '400',
},
'code::before': {
content: '""',
},
'code::after': {
content: '""',
},
pre: {
backgroundColor: 'var(--color-background-alt)',
},
blockquote: {
color: 'var(--color-foreground-alt)',
borderLeftColor: 'var(--color-primary-500)',
},
hr: {
borderColor: 'var(--color-border)',
},
strong: {
color: 'var(--color-foreground)',
},
'ul li::marker': {
color: 'var(--color-primary-500)',
},
'ol li::marker': {
color: 'var(--color-primary-500)',
},
},
},
},
},
},
plugins: [
require('@tailwindcss/typography'),
],
}

5
tsconfig.json Normal file
View File

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