首次提交:姜十三论坛

后端 Go+Gin:认证/CSRF/限流、板块、帖子、评论、点赞、通知、用户资料、置顶推荐;前端 Next.js 16:发帖/编辑/删除、搜索、分页、点赞、通知中心、设置;基础设施 docker-compose 与配置模板;添加 .gitignore 与专有许可证(保留所有权利)
This commit is contained in:
2026-09-12 01:11:05 +08:00
commit 0c2b0d2d6a
62 changed files with 8289 additions and 0 deletions

View File

@@ -0,0 +1,121 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Trash2 } from "lucide-react";
import { apiCreateComment, apiDeleteComment, apiMe, type Comment, type User } from "@/lib/api";
interface CommentSectionProps {
postId: string;
comments: Comment[];
}
export default function CommentSection({ postId, comments }: CommentSectionProps) {
const router = useRouter();
const [content, setContent] = useState("");
const [submitting, setSubmitting] = useState(false);
const [user, setUser] = useState<User | null>(null);
const [deletingId, setDeletingId] = useState<number | null>(null);
useEffect(() => {
apiMe()
.then((res) => setUser(res.user || null))
.catch(() => setUser(null));
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim()) return;
setSubmitting(true);
try {
const res = await apiCreateComment(postId, content);
if (res.comment) {
setContent("");
router.refresh();
} else if (res.error === "未登录") {
router.push("/login");
} else {
alert(res.error || "评论失败");
}
} finally {
setSubmitting(false);
}
};
const handleDelete = async (commentId: number) => {
if (!confirm("确定要删除这条评论吗?")) return;
setDeletingId(commentId);
try {
const res = await apiDeleteComment(postId, commentId);
if (res.message) {
router.refresh();
} else {
alert(res.error || "删除失败");
}
} finally {
setDeletingId(null);
}
};
const canDelete = (comment: Comment) =>
user && (user.id === comment.user.id || user.role === "admin");
return (
<section className="mt-8 pt-6 border-t" style={{ borderColor: "var(--border)" }}>
<h2 className="text-xl font-bold mb-4">评论 ({comments.length})</h2>
<form onSubmit={handleSubmit} className="mb-6">
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder="写下你的评论..."
className="w-full p-3 rounded-lg border resize-none h-24"
style={{ borderColor: "var(--border)", background: "var(--bg)", color: "var(--text)" }}
/>
<button
type="submit"
disabled={submitting || !content.trim()}
className="mt-2 px-4 py-2 rounded-lg text-white disabled:opacity-50"
style={{ background: "var(--primary)" }}
>
{submitting ? "发送中..." : "发表评论"}
</button>
</form>
<div className="space-y-4">
{comments.map((comment) => (
<div key={comment.id} className="p-4 rounded-lg" style={{ background: "var(--bg-secondary)" }}>
<div className="flex items-center justify-between mb-2">
<div className="flex items-center gap-2">
<Link href={`/u/${comment.user.id}`} className="font-medium hover:underline" style={{ color: "var(--primary)" }}>
{comment.user.nickname}
</Link>
<span className="text-sm" style={{ color: "var(--text-secondary)" }}>
{new Date(comment.created_at).toLocaleString("zh-CN")}
</span>
</div>
{canDelete(comment) && (
<button
onClick={() => handleDelete(comment.id)}
disabled={deletingId === comment.id}
className="flex items-center gap-1 text-sm text-red-600 hover:opacity-80 disabled:opacity-50"
>
<Trash2 size={14} />
{deletingId === comment.id ? "删除中" : "删除"}
</button>
)}
</div>
<p style={{ color: "var(--text)" }}>{comment.content}</p>
</div>
))}
{comments.length === 0 && (
<p className="text-center py-8" style={{ color: "var(--text-secondary)" }}>
暂无评论,来抢沙发吧!
</p>
)}
</div>
</section>
);
}

View File

@@ -0,0 +1,7 @@
export default function Footer() {
return (
<footer className="border-t py-6 text-center text-sm" style={{ borderColor: "var(--border)", color: "var(--text-secondary)" }}>
<p>姜十三论坛 · Powered by Go 1.27 + Next.js 16</p>
</footer>
);
}

View File

@@ -0,0 +1,151 @@
"use client";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useState, useEffect } from "react";
import { Menu, X, Sun, Moon, LogIn, UserPlus, LogOut, PenSquare, Search, Settings } from "lucide-react";
import { apiMe, apiLogout, type User } from "@/lib/api";
import NotificationBell from "./NotificationBell";
export default function Header() {
const router = useRouter();
const [menuOpen, setMenuOpen] = useState(false);
const [theme, setTheme] = useState<"light" | "dark">("light");
const [user, setUser] = useState<User | null>(null);
const [searchQuery, setSearchQuery] = useState("");
const handleSearch = (e: React.FormEvent) => {
e.preventDefault();
const q = searchQuery.trim();
if (q) {
router.push(`/?q=${encodeURIComponent(q)}`);
}
};
useEffect(() => {
// 读取主题
const savedTheme = document.documentElement.classList.contains("dark") ? "dark" : "light";
setTheme(savedTheme);
// 从后端获取登录态(HttpOnly cookie 自动携带)
apiMe()
.then((res) => setUser(res.user || null))
.catch(() => setUser(null));
}, []);
const toggleTheme = () => {
const newTheme = theme === "dark" ? "light" : "dark";
setTheme(newTheme);
document.documentElement.classList.toggle("dark", newTheme === "dark");
document.cookie = `j13-theme=${newTheme}; path=/; max-age=31536000`;
};
const handleLogout = async () => {
try {
await apiLogout();
} catch {
/* ignore */
}
setUser(null);
setMenuOpen(false);
router.refresh();
};
return (
<header className="sticky top-0 z-50 border-b" style={{ borderColor: "var(--border)", background: "var(--bg)" }}>
<div className="max-w-5xl mx-auto px-4 h-14 flex items-center justify-between">
<Link href="/" className="font-bold text-lg" style={{ color: "var(--primary)" }}>
姜十三论坛
</Link>
{/* 桌面端导航 */}
<nav className="hidden md:flex items-center gap-4">
<form onSubmit={handleSearch} className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-secondary)" }} />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索帖子..."
className="pl-9 pr-3 py-1.5 rounded-lg text-sm w-44 focus:outline-none focus:w-56 transition-all"
style={{ background: "var(--bg-secondary)", color: "var(--text)", border: "1px solid var(--border)" }}
/>
</form>
<Link href="/" className="hover:opacity-80" style={{ color: "var(--text)" }}>首页</Link>
{user && (
<Link href="/compose" className="flex items-center gap-1 hover:opacity-80" style={{ color: "var(--text)" }}>
<PenSquare size={16} /> 发帖
</Link>
)}
<button onClick={toggleTheme} className="p-2 rounded-lg hover:opacity-80" style={{ color: "var(--text)" }}>
{theme === "dark" ? <Sun size={18} /> : <Moon size={18} />}
</button>
{user && <NotificationBell />}
{user ? (
<div className="flex items-center gap-3">
<span className="text-sm" style={{ color: "var(--text-secondary)" }}>{user.nickname}</span>
<Link href="/settings" className="flex items-center gap-1 text-sm hover:opacity-80" style={{ color: "var(--text-secondary)" }}>
<Settings size={14} /> 设置
</Link>
<button onClick={handleLogout} className="flex items-center gap-1 text-sm hover:opacity-80" style={{ color: "var(--text-secondary)" }}>
<LogOut size={14} /> 退出
</button>
</div>
) : (
<div className="flex items-center gap-2">
<Link href="/login" className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm" style={{ background: "var(--bg-secondary)", color: "var(--text)" }}>
<LogIn size={14} /> 登录
</Link>
<Link href="/register" className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm text-white" style={{ background: "var(--primary)" }}>
<UserPlus size={14} /> 注册
</Link>
</div>
)}
</nav>
{/* 移动端菜单按钮 */}
<button onClick={() => setMenuOpen(!menuOpen)} className="md:hidden p-2" style={{ color: "var(--text)" }}>
{menuOpen ? <X size={20} /> : <Menu size={20} />}
</button>
</div>
{/* 移动端下拉菜单 */}
{menuOpen && (
<div className="md:hidden border-t px-4 py-3 space-y-2" style={{ borderColor: "var(--border)", background: "var(--bg)" }}>
<form onSubmit={(e) => { handleSearch(e); setMenuOpen(false); }} className="relative">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2" style={{ color: "var(--text-secondary)" }} />
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
placeholder="搜索帖子..."
className="w-full pl-9 pr-3 py-2 rounded-lg text-sm"
style={{ background: "var(--bg-secondary)", color: "var(--text)", border: "1px solid var(--border)" }}
/>
</form>
<Link href="/" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>首页</Link>
{user && (
<Link href="/compose" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>发帖</Link>
)}
<button onClick={toggleTheme} className="block py-2 w-full text-left" style={{ color: "var(--text)" }}>
{theme === "dark" ? "切换亮色主题" : "切换暗色主题"}
</button>
{user ? (
<Link href="/notifications" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>通知中心</Link>
) : null}
{user ? (
<>
<Link href="/settings" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>账号设置</Link>
<button onClick={handleLogout} className="block py-2 w-full text-left" style={{ color: "var(--text)" }}>退出登录</button>
</>
) : (
<>
<Link href="/login" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>登录</Link>
<Link href="/register" onClick={() => setMenuOpen(false)} className="block py-2" style={{ color: "var(--text)" }}>注册</Link>
</>
)}
</div>
)}
</header>
);
}

View File

@@ -0,0 +1,50 @@
"use client";
import { useState } from "react";
import { Heart } from "lucide-react";
import { apiToggleLike } from "@/lib/api";
interface LikeButtonProps {
postId: string;
liked: boolean;
likeCount: number;
}
export default function LikeButton({ postId, liked: initialLiked, likeCount: initialCount }: LikeButtonProps) {
const [liked, setLiked] = useState(initialLiked);
const [count, setCount] = useState(initialCount);
const [loading, setLoading] = useState(false);
const handleClick = async () => {
if (loading) return;
setLoading(true);
try {
const res = await apiToggleLike(postId);
if (res.error === "未登录") {
window.location.href = "/login";
return;
}
if (typeof res.liked === "boolean") {
setLiked(res.liked);
setCount(res.like_count ?? count);
}
} finally {
setLoading(false);
}
};
return (
<button
onClick={handleClick}
disabled={loading}
className={`flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm font-medium transition-all disabled:opacity-50 ${
liked
? "text-red-500 bg-red-50 dark:bg-red-900/20"
: "text-gray-500 hover:text-red-500 hover:bg-gray-100 dark:hover:bg-gray-800"
}`}
>
<Heart size={16} fill={liked ? "currentColor" : "none"} />
<span>{count}</span>
</button>
);
}

View File

@@ -0,0 +1,197 @@
"use client";
import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Bell, CheckCheck, Heart, MessageCircle } from "lucide-react";
import {
apiFetchNotifications,
apiUnreadCount,
apiMarkRead,
apiMarkAllRead,
type NotificationItem,
} from "@/lib/api";
export default function NotificationBell() {
const router = useRouter();
const [open, setOpen] = useState(false);
const [unread, setUnread] = useState(0);
const [notifications, setNotifications] = useState<NotificationItem[]>([]);
const [loading, setLoading] = useState(false);
const dropdownRef = useRef<HTMLDivElement>(null);
// 轮询未读数(30 秒)
useEffect(() => {
const fetchCount = () => {
apiUnreadCount()
.then((res) => setUnread(res.count || 0))
.catch(() => {});
};
fetchCount();
const timer = setInterval(fetchCount, 30000);
return () => clearInterval(timer);
}, []);
// 点击外部关闭下拉
useEffect(() => {
const handleClick = (e: MouseEvent) => {
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setOpen(false);
}
};
document.addEventListener("mousedown", handleClick);
return () => document.removeEventListener("mousedown", handleClick);
}, []);
const loadNotifications = async () => {
setLoading(true);
try {
const res = await apiFetchNotifications(1);
setNotifications(res.notifications || []);
} catch {
setNotifications([]);
}
setLoading(false);
};
const handleToggle = () => {
const next = !open;
setOpen(next);
if (next) {
loadNotifications();
}
};
const handleClickNotification = async (n: NotificationItem) => {
if (!n.is_read) {
apiMarkRead(n.id).catch(() => {});
setUnread((c) => Math.max(0, c - 1));
setNotifications((list) =>
list.map((item) => (item.id === n.id ? { ...item, is_read: true } : item))
);
}
setOpen(false);
router.push(`/post/${n.post_id}`);
};
const handleMarkAllRead = async () => {
await apiMarkAllRead();
setUnread(0);
setNotifications((list) => list.map((item) => ({ ...item, is_read: true })));
};
const formatTime = (dateStr: string) => {
const diff = Date.now() - new Date(dateStr).getTime();
const min = Math.floor(diff / 60000);
if (min < 1) return "刚刚";
if (min < 60) return `${min} 分钟前`;
const hour = Math.floor(min / 60);
if (hour < 24) return `${hour} 小时前`;
const day = Math.floor(hour / 24);
return `${day} 天前`;
};
const actionText = (n: NotificationItem) => {
if (n.type === "comment") return "评论了你的帖子";
return "点赞了你的帖子";
};
return (
<div className="relative" ref={dropdownRef}>
<button
onClick={handleToggle}
className="relative p-2 rounded-lg hover:opacity-80"
style={{ color: "var(--text)" }}
aria-label="通知"
>
<Bell size={18} />
{unread > 0 && (
<span
className="absolute -top-0.5 -right-0.5 min-w-[16px] h-4 px-1 rounded-full text-xs text-white flex items-center justify-center font-bold"
style={{ background: "var(--primary)" }}
>
{unread > 99 ? "99+" : unread}
</span>
)}
</button>
{open && (
<div
className="absolute right-0 mt-2 w-80 rounded-xl border shadow-xl overflow-hidden z-50"
style={{ borderColor: "var(--border)", background: "var(--bg)" }}
>
<div
className="flex items-center justify-between px-4 py-3 border-b"
style={{ borderColor: "var(--border)" }}
>
<span className="font-semibold" style={{ color: "var(--text)" }}>通知</span>
{unread > 0 && (
<button
onClick={handleMarkAllRead}
className="flex items-center gap-1 text-xs hover:opacity-80"
style={{ color: "var(--primary)" }}
>
<CheckCheck size={14} /> 全部已读
</button>
)}
</div>
<div className="max-h-96 overflow-y-auto">
{loading ? (
<p className="text-center py-8 text-sm" style={{ color: "var(--text-secondary)" }}>加载中...</p>
) : notifications.length === 0 ? (
<p className="text-center py-8 text-sm" style={{ color: "var(--text-secondary)" }}>暂无通知</p>
) : (
notifications.map((n) => (
<button
key={n.id}
onClick={() => handleClickNotification(n)}
className="w-full text-left px-4 py-3 border-b hover:opacity-90 transition-opacity"
style={{
borderColor: "var(--border)",
background: n.is_read ? "transparent" : "var(--bg-secondary)",
}}
>
<div className="flex items-start gap-2">
<span style={{ color: n.type === "like" ? "#ef4444" : "var(--primary)" }}>
{n.type === "like" ? <Heart size={16} /> : <MessageCircle size={16} />}
</span>
<div className="flex-1 min-w-0">
<p className="text-sm" style={{ color: "var(--text)" }}>
<span className="font-medium">{n.actor.nickname}</span>{" "}
<span style={{ color: "var(--text-secondary)" }}>{actionText(n)}</span>
</p>
<p className="text-xs mt-0.5 truncate" style={{ color: "var(--text-secondary)" }}>
《{n.post.title}》
</p>
{n.content && (
<p className="text-xs mt-1 line-clamp-1" style={{ color: "var(--text-secondary)" }}>
{n.content}
</p>
)}
<p className="text-xs mt-1" style={{ color: "var(--text-secondary)" }}>
{formatTime(n.created_at)}
</p>
</div>
{!n.is_read && (
<span
className="w-2 h-2 rounded-full shrink-0 mt-1.5"
style={{ background: "var(--primary)" }}
/>
)}
</div>
</button>
))
)}
</div>
<div className="px-4 py-2 border-t text-center" style={{ borderColor: "var(--border)" }}>
<Link href="/notifications" className="text-sm hover:underline" style={{ color: "var(--primary)" }}>
查看全部通知
</Link>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,95 @@
"use client";
import Link from "next/link";
import { ChevronLeft, ChevronRight } from "lucide-react";
interface PaginationProps {
total: number;
page: number;
size: number;
basePath: string; // e.g. "/" or "/board/1"
query?: Record<string, string>; // additional query params (e.g. q for search)
onChange?: (page: number) => void; // 客户端分页回调;提供时不渲染 Link 而是按钮
}
export default function Pagination({ total, page, size, basePath, query = {}, onChange }: PaginationProps) {
const totalPages = Math.max(1, Math.ceil(total / size));
if (totalPages <= 1) return null;
const buildHref = (p: number) => {
const params = new URLSearchParams(query);
params.set("page", String(p));
return `${basePath}?${params.toString()}`;
};
const handleClick = (p: number, e: React.MouseEvent) => {
if (onChange) {
e.preventDefault();
onChange(p);
}
};
// 生成页码按钮(最多显示 7 个,带省略号)
const pages: (number | "...")[] = [];
const add = (p: number | "...") => pages.push(p);
if (totalPages <= 7) {
for (let i = 1; i <= totalPages; i++) add(i);
} else {
add(1);
if (page > 4) add("...");
const start = Math.max(2, page - 1);
const end = Math.min(totalPages - 1, page + 1);
for (let i = start; i <= end; i++) add(i);
if (page < totalPages - 3) add("...");
add(totalPages);
}
return (
<nav className="flex items-center justify-center gap-1 mt-8">
{page > 1 && (
<Link
href={buildHref(page - 1)}
onClick={(e) => handleClick(page - 1, e)}
className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm hover:opacity-80"
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
>
<ChevronLeft size={16} /> 上一页
</Link>
)}
{pages.map((p, i) =>
p === "..." ? (
<span key={`e${i}`} className="px-2" style={{ color: "var(--text-secondary)" }}>…</span>
) : (
<Link
key={p}
href={buildHref(p)}
onClick={(e) => handleClick(p, e)}
className={`min-w-[36px] h-9 flex items-center justify-center rounded-lg text-sm ${
p === page ? "text-white" : "hover:opacity-80"
}`}
style={
p === page
? { background: "var(--primary)" }
: { background: "var(--bg-secondary)", color: "var(--text)" }
}
>
{p}
</Link>
)
)}
{page < totalPages && (
<Link
href={buildHref(page + 1)}
onClick={(e) => handleClick(page + 1, e)}
className="flex items-center gap-1 px-3 py-1.5 rounded-lg text-sm hover:opacity-80"
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
>
下一页 <ChevronRight size={16} />
</Link>
)}
</nav>
);
}

View File

@@ -0,0 +1,117 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import Link from "next/link";
import { Pencil, Trash2, Pin, Star } from "lucide-react";
import { apiMe, apiDeletePost, apiTogglePin, apiToggleRecommend, type User } from "@/lib/api";
interface PostActionsProps {
postId: string;
authorId: number;
pinned: number;
recommended: boolean;
}
export default function PostActions({ postId, authorId, pinned, recommended }: PostActionsProps) {
const router = useRouter();
const [user, setUser] = useState<User | null>(null);
const [deleting, setDeleting] = useState(false);
const [isPinned, setIsPinned] = useState(pinned > 0);
const [isRecommended, setIsRecommended] = useState(recommended);
const [acting, setActing] = useState("");
useEffect(() => {
apiMe()
.then((res) => setUser(res.user || null))
.catch(() => setUser(null));
}, []);
// 仅作者本人或管理员可编辑/删除;置顶/推荐仅管理员
const canManage = user && (user.id === authorId || user.role === "admin");
const isAdmin = user?.role === "admin";
if (!canManage) return null;
const handleDelete = async () => {
if (!confirm("确定要删除这篇帖子吗?此操作不可恢复。")) return;
setDeleting(true);
try {
const res = await apiDeletePost(postId);
if (res.message) {
router.push("/");
} else {
alert(res.error || "删除失败");
}
} finally {
setDeleting(false);
}
};
const handlePin = async () => {
setActing("pin");
try {
const res = await apiTogglePin(postId);
setIsPinned(res.pinned > 0);
router.refresh();
} finally {
setActing("");
}
};
const handleRecommend = async () => {
setActing("recommend");
try {
const res = await apiToggleRecommend(postId);
setIsRecommended(res.recommended);
router.refresh();
} finally {
setActing("");
}
};
return (
<div className="flex items-center gap-2 flex-wrap justify-end">
{isAdmin && (
<>
<button
onClick={handlePin}
disabled={acting !== ""}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg hover:opacity-80 disabled:opacity-50"
style={{
background: isPinned ? "var(--primary)" : "var(--bg-secondary)",
color: isPinned ? "white" : "var(--text)",
}}
>
<Pin size={14} /> {isPinned ? "取消置顶" : "置顶"}
</button>
<button
onClick={handleRecommend}
disabled={acting !== ""}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg hover:opacity-80 disabled:opacity-50"
style={{
background: isRecommended ? "#e11d48" : "var(--bg-secondary)",
color: isRecommended ? "white" : "var(--text)",
}}
>
<Star size={14} /> {isRecommended ? "取消推荐" : "推荐"}
</button>
</>
)}
<Link
href={`/post/${postId}/edit`}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg hover:opacity-80"
style={{ background: "var(--bg-secondary)", color: "var(--text)" }}
>
<Pencil size={14} /> 编辑
</Link>
<button
onClick={handleDelete}
disabled={deleting}
className="flex items-center gap-1 text-sm px-3 py-1.5 rounded-lg text-red-600 hover:bg-red-50 disabled:opacity-50"
style={{ background: "var(--bg-secondary)" }}
>
<Trash2 size={14} /> {deleting ? "删除中..." : "删除"}
</button>
</div>
);
}