Files
fanqie-go/internal/handlers/review.go
T
chenxin d710d382ee 🐛 fix(server): 增加优雅退出与请求超时保护
- 新增 SIGINT/SIGTERM 信号处理与 http.Server.Shutdown,退出前确保统计数据保存、数据库正常关闭
- 为 http.Server 设置 ReadHeaderTimeout/ReadTimeout/WriteTimeout/IdleTimeout,防止慢客户端长期占用连接
- 全局配置指针改为 atomic.Pointer 并提供 GetAppConfig 访问器,消除配置热更新时的数据竞争,同时删除冗余的 manager.config 字段
- 请求统计九组计数器重构为 map[string]*atomic.Int64,统一 incrementStat/getStatsSnapshot 访问,精简约 40 行样板代码
- go mod tidy 清理 go.mod 与 go.sum 中的冗余依赖条目
2026-09-29 19:47:04 +08:00

1282 lines
41 KiB
Go

package handlers
import (
"encoding/json"
"fanqie/internal/fqapi"
"fmt"
"net/http"
"strconv"
"strings"
"time"
)
// validateParams 验证必需参数
func validateParams(r *http.Request, required ...string) (map[string]string, error) {
params := make(map[string]string)
for _, key := range required {
value := r.URL.Query().Get(key)
if value == "" {
return nil, fmt.Errorf("缺少 %s 参数", key)
}
params[key] = value
}
return params, nil
}
// getOptionalParam 获取可选参数(带默认值)
func getOptionalParam(r *http.Request, key, defaultValue string) string {
value := r.URL.Query().Get(key)
if value == "" {
return defaultValue
}
return value
}
// parseIntParam 解析整数参数
func parseIntParam(value string, paramName string) (int, error) {
if value == "" {
return 0, nil
}
result, err := strconv.Atoi(value)
if err != nil {
return 0, fmt.Errorf("%s 参数格式错误", paramName)
}
return result, nil
}
// handleReviewError 统一处理段评 API 错误
func handleReviewError(w http.ResponseWriter, errType string, err error) {
status := http.StatusInternalServerError
msg := fmt.Sprintf("%s失败: %s", errType, err.Error())
if strings.Contains(err.Error(), "缺少") || strings.Contains(err.Error(), "格式错误") {
status = http.StatusBadRequest
}
respondJSON(w, status, map[string]interface{}{
"code": -1,
"msg": msg,
})
}
// handleReviewSuccess 统一处理成功响应
func handleReviewSuccess(w http.ResponseWriter, data interface{}) {
respondJSON(w, http.StatusOK, map[string]interface{}{
"code": 0,
"msg": "ok",
"data": data,
})
}
// HandleChapterReview 处理章节评论请求(混合数据)
func HandleChapterReview(w http.ResponseWriter, r *http.Request) {
incrementStat("total")
// 验证必需参数
params, err := validateParams(r, "item_id")
if err != nil {
handleReviewError(w, "参数验证", err)
return
}
// 获取可选参数
bookID := getOptionalParam(r, "book_id", "")
// 调用 API
data, err := fqapi.GetChapterMixData(bookID, params["item_id"])
if err != nil {
handleReviewError(w, "获取章节评论", err)
return
}
handleReviewSuccess(w, data)
}
// HandleReview 处理段落评论请求
func HandleReview(w http.ResponseWriter, r *http.Request) {
incrementStat("total")
// 验证必需参数
params, err := validateParams(r, "item_id")
if err != nil {
handleReviewError(w, "参数验证", err)
return
}
// 获取可选参数
bookID := getOptionalParam(r, "book_id", "")
commentID := getOptionalParam(r, "comment_id", "")
paraStr := getOptionalParam(r, "para", "0")
sortStr := getOptionalParam(r, "sort", "1")
offsetStr := getOptionalParam(r, "offset", "0")
countStr := getOptionalParam(r, "count", "20")
// 解析整数参数
para, err := parseIntParam(paraStr, "para")
if err != nil {
handleReviewError(w, "参数解析", err)
return
}
sort, err := parseIntParam(sortStr, "sort")
if err != nil {
sort = 1 // 默认热门
}
offset, _ := parseIntParam(offsetStr, "offset")
count, _ := parseIntParam(countStr, "count")
if count <= 0 {
count = 20
}
// 调用 API
data, err := fqapi.GetParaReview(params["item_id"], bookID, commentID, para, sort, offset, count)
if err != nil {
handleReviewError(w, "获取段落评论", err)
return
}
handleReviewSuccess(w, data)
}
// HandleReviewHTML 处理段落评论 HTML 显示
func HandleReviewHTML(w http.ResponseWriter, r *http.Request) {
incrementStat("total")
// 验证必需参数
params, err := validateParams(r, "item_id", "para")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "<html><body><h3>%s</h3></body></html>", err.Error())
return
}
// 解析整数参数
para, err := parseIntParam(params["para"], "para")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "<html><body><h3>%s</h3></body></html>", err.Error())
return
}
// 获取可选参数
bookID := getOptionalParam(r, "book_id", "")
pageStr := getOptionalParam(r, "page", "1")
pageSizeStr := getOptionalParam(r, "page_size", "20")
sortStr := getOptionalParam(r, "sort", "1")
// 解析分页参数
page, _ := parseIntParam(pageStr, "page")
if page < 1 {
page = 1
}
pageSize, _ := parseIntParam(pageSizeStr, "page_size")
if pageSize < 1 || pageSize > 100 {
pageSize = 20
}
// 解析排序参数
sort, _ := parseIntParam(sortStr, "sort")
if sort != 1 && sort != 3 {
sort = 1 // 默认热门
}
// 计算 offset(基于页码)
offset := (page - 1) * pageSize
// 调用 API
data, err := fqapi.GetParaReview(params["item_id"], bookID, "", para, sort, offset, pageSize)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, "<html><body><h3>获取评论失败: %s</h3></body></html>", err.Error())
return
}
// 如果是 AJAX 请求,直接返回 JSON 数据
if r.Header.Get("X-Requested-With") == "XMLHttpRequest" {
respondJSON(w, http.StatusOK, map[string]interface{}{
"code": 0,
"data": data,
})
return
}
// 生成完整 HTML 页面(仅首次加载)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
html := generateReviewHTML(data, params["item_id"], bookID, para, page, pageSize, sort)
fmt.Fprint(w, html)
}
// 在 init 函数中初始化表情管理器
func init() {
// 初始化表情管理器
em := fqapi.GetEmojiManager()
em.LoadEmojis()
}
// replaceEmojiWithImages 将表情文本替换为图片标签
func replaceEmojiWithImages(text string) string {
return fqapi.ReplaceEmojisInText(text)
}
// parseCommentData 解析评论数据的通用函数
type CommentInfo struct {
UserName string
UserAvatar string
IsAuthor bool
StickerImageURL string
CreateTime string
CommentText string
CommentID string
DiggCount int
ReplyCount int
ImageURL string
ImageLargeURL string
}
func parseCommentData(comment map[string]interface{}) CommentInfo {
info := CommentInfo{
UserName: "匿名用户",
}
// 提取 comment_id
if cid, ok := comment["comment_id"].(string); ok {
info.CommentID = cid
}
// 用户信息
if userInfo, ok := comment["user_info"].(map[string]interface{}); ok {
if name, ok := userInfo["user_name"].(string); ok {
info.UserName = name
}
if avatar, ok := userInfo["user_avatar"].(string); ok {
info.UserAvatar = avatar
}
if author, ok := userInfo["is_author"].(bool); ok {
info.IsAuthor = author
}
}
// 创建时间
if timestamp, ok := comment["create_timestamp"].(float64); ok {
t := time.Unix(int64(timestamp), 0)
info.CreateTime = t.Format("2006-01-02 15:04")
}
// 评论内容
if text, ok := comment["text"].(string); ok {
info.CommentText = text
}
// 提取图片
if imageData, ok := comment["image_data"].([]interface{}); ok && len(imageData) > 0 {
if imgMap, ok := imageData[0].(map[string]interface{}); ok {
if url, ok := imgMap["web_uri"].(string); ok && url != "" {
info.ImageURL = url
}
if largeURL, ok := imgMap["expand_web_url"].(string); ok && largeURL != "" {
info.ImageLargeURL = largeURL
} else {
info.ImageLargeURL = info.ImageURL
}
}
}
// 统计信息
if count, ok := comment["digg_count"].(float64); ok {
info.DiggCount = int(count)
} else if count, ok := comment["digg_count"].(int); ok {
info.DiggCount = count
}
// 回复数量
if replyCountVal, ok := comment["reply_count"].(float64); ok {
info.ReplyCount = int(replyCountVal)
} else if replyCountVal, ok := comment["reply_count"].(int); ok {
info.ReplyCount = replyCountVal
} else if replyCnt, ok := comment["reply_cnt"].(float64); ok {
info.ReplyCount = int(replyCnt)
} else if replyCnt, ok := comment["reply_cnt"].(int); ok {
info.ReplyCount = replyCnt
}
return info
}
// generateReviewHTML 生成评论 HTML 页面
func generateReviewHTML(data map[string]interface{}, itemID, bookID string, para, page, pageSize, sort int) string {
var html strings.Builder
html.WriteString(`<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>番茄段评 · 第 `)
html.WriteString(strconv.Itoa(para + 1))
html.WriteString(` 段</title>
<link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.css">
<meta name="color-scheme" content="light dark">
<style>
:root {
/* 浅色模式变量 */
--bg-primary: #f5f5f5;
--bg-secondary: #ffffff;
--text-primary: #333333;
--text-secondary: #666666;
--text-tertiary: #999999;
--border-color: #e5e5e5;
--shadow: rgba(0, 0, 0, 0.05);
--badge-bg: #f0f5ff;
--badge-color: #4a80f0;
--tag-bg: #f0f0f0;
--tag-color: #666666;
--avatar-bg: #f0f0f0;
--loading-color: #666666;
}
/* 深色模式变量 */
@media (prefers-color-scheme: dark) {
:root {
--bg-primary: #000000;
--bg-secondary: #1c1c1e;
--text-primary: #ffffff;
--text-secondary: #ebebf5;
--text-tertiary: #8e8e93;
--border-color: #38383a;
--shadow: rgba(0, 0, 0, 0.3);
--badge-bg: #1c3a5f;
--badge-color: #64a3ff;
--tag-bg: #2c2c2e;
--tag-color: #ebebf5;
--avatar-bg: #2c2c2e;
--loading-color: #8e8e93;
}
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
}
body {
background-color: var(--bg-primary);
color: var(--text-primary);
padding: 15px;
max-width: 600px;
margin: 0 auto;
transition: background-color 0.3s ease, color 0.3s ease;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding: 10px 15px;
background: var(--bg-secondary);
border-radius: 12px;
box-shadow: 0 2px 8px var(--shadow);
transition: background-color 0.3s ease;
}
.header h1 {
font-size: 18px;
color: var(--text-primary);
margin: 0;
flex: 1;
}
.source-tag {
display: inline-block;
padding: 3px 8px;
background-color: var(--tag-bg);
border-radius: 4px;
font-size: 14px;
margin-left: 8px;
color: var(--tag-color);
transition: background-color 0.3s ease, color 0.3s ease;
}
.comment-item {
background: var(--bg-secondary);
border-radius: 12px;
padding: 15px;
box-shadow: 0 2px 8px var(--shadow);
margin-bottom: 15px;
transition: background-color 0.3s ease;
}
.user-info {
display: flex;
align-items: center;
margin-bottom: 10px;
}
.user-avatar, .reply-avatar {
width: 40px;
height: 40px;
border-radius: 50%;
margin-right: 10px;
background: var(--avatar-bg);
object-fit: cover;
}
.reply-avatar {
width: 32px;
height: 32px;
}
.user-name {
font-weight: 500;
font-size: 15px;
color: var(--text-primary);
}
.author-badge {
background: var(--badge-bg);
color: var(--badge-color);
font-size: 12px;
padding: 0 6px;
border-radius: 3px;
margin-left: 6px;
}
.user-sticker {
height: 18px;
margin-left: 6px;
vertical-align: middle;
}
.comment-content {
font-size: 15px;
line-height: 1.5;
margin-bottom: 10px;
white-space: pre-line;
}
.comment-img {
max-width: 100%;
border-radius: 6px;
margin: 8px 0;
cursor: pointer;
background: #eee;
}
.emoji-img {
width: 22px;
height: 22px;
vertical-align: middle;
margin: 0 2px;
}
.comment-time {
font-size: 12px;
color: var(--text-tertiary);
margin-bottom: 10px;
}
.comment-meta {
display: flex;
align-items: center;
gap: 15px;
font-size: 13px;
color: var(--text-secondary);
}
.comment-meta i {
margin-right: 4px;
font-size: 14px;
}
.comment-meta span {
cursor: pointer;
display: inline-flex;
align-items: center;
padding: 4px 8px;
border-radius: 6px;
transition: all 0.2s ease;
}
.comment-meta span:hover {
background: var(--bg-secondary);
color: var(--text-primary);
}
.comment-meta span:hover i {
transform: scale(1.1);
}
.reply-btn {
transition: all 0.2s ease;
}
.reply-btn:active {
transform: scale(0.95);
opacity: 0.4;
}
.replies-container {
margin-top: 15px;
padding-left: 25px;
position: relative;
display: none;
}
.replies-container.show {
display: block;
}
.replies-container::before {
content: '';
position: absolute;
left: 8px;
top: 0;
bottom: 0;
width: 2px;
background: var(--border-color);
}
.reply-item {
display: flex;
align-items: flex-start;
margin-bottom: 15px;
}
.reply-content {
flex: 1;
padding-top: 2px;
}
.reply-username {
font-weight: 500;
font-size: 14px;
margin-right: 5px;
color: var(--text-primary);
}
.reply-text {
font-size: 14px;
line-height: 1.4;
margin: 5px 0;
color: var(--text-primary);
}
.reply-time {
font-size: 11px;
color: var(--text-tertiary);
margin-top: 3px;
}
.image-viewer {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.9);
display: none;
justify-content: center;
align-items: center;
z-index: 1000;
}
.image-viewer.show {
display: flex;
}
.image-viewer img {
max-width: 90%;
max-height: 90%;
}
.close-btn {
position: absolute;
top: 20px;
right: 20px;
color: #fff;
font-size: 30px;
cursor: pointer;
}
.empty, .loading {
text-align: center;
color: var(--text-tertiary);
}
.empty {
padding: 20px;
background: var(--bg-secondary);
border-radius: 12px;
}
.loading {
padding: 10px;
color: var(--loading-color);
}
.sort-tabs {
display: flex;
gap: 0;
background: var(--bg-primary);
border-radius: 20px;
padding: 3px;
}
.sort-tab {
padding: 6px 16px;
background: transparent;
border: none;
border-radius: 17px;
cursor: pointer;
font-size: 14px;
color: var(--text-secondary);
transition: all 0.2s ease;
user-select: none;
white-space: nowrap;
}
.sort-tab.active {
background: var(--bg-secondary);
color: var(--text-primary);
font-weight: 500;
box-shadow: 0 1px 3px var(--shadow);
}
.sort-tab:hover:not(.active) {
opacity: 0.7;
}
.back-to-top {
position: fixed;
bottom: 30px;
right: 30px;
width: 50px;
height: 50px;
background: var(--bg-secondary);
border-radius: 50%;
display: none;
align-items: center;
justify-content: center;
cursor: pointer;
box-shadow: 0 4px 12px var(--shadow);
transition: all 0.3s ease;
z-index: 999;
border: 1px solid var(--border-color);
}
.back-to-top.show {
display: flex;
}
.back-to-top:hover {
transform: translateY(-5px);
box-shadow: 0 6px 16px var(--shadow);
}
.back-to-top i {
font-size: 20px;
color: var(--text-primary);
}
</style>
</head>
<body>
<div class="header">
<h1><span class="source-tag">段落评论 · `)
// 提取评论总数和是否有更多
total := 0
hasMore := false
nextOffset := 0
// 新接口返回 count 字段表示总数
if countVal, ok := data["count"].(float64); ok {
total = int(countVal)
} else if countVal, ok := data["count"].(int); ok {
total = countVal
}
// 检查是否有更多数据
if hasMoreVal, ok := data["has_more"].(bool); ok {
hasMore = hasMoreVal
} else if hasMoreVal, ok := data["has_more"].(float64); ok {
hasMore = hasMoreVal > 0
} else if hasMoreVal, ok := data["has_more"].(int); ok {
hasMore = hasMoreVal > 0
}
// 获取下一页的 offset
if nextOffsetVal, ok := data["next_offset"].(float64); ok {
nextOffset = int(nextOffsetVal)
} else if nextOffsetVal, ok := data["next_offset"].(int); ok {
nextOffset = nextOffsetVal
}
html.WriteString(strconv.Itoa(total))
html.WriteString(` 条</span></h1>
<span style="display: flex; align-items: center;">
<i class="fas fa-book-open" style="color: var(--text-tertiary); font-size: 16px; margin: 0 10px;"></i>
</span>
<div class="sort-tabs">
<div class="sort-tab`)
if sort == 1 {
html.WriteString(` active`)
}
html.WriteString(`" onclick="switchSort(1)">最热</div>
<div class="sort-tab`)
if sort == 3 {
html.WriteString(` active`)
}
html.WriteString(`" onclick="switchSort(3)">最新</div>
</div>
</div>
`)
// 解析评论数据
comments := []map[string]interface{}{}
if commentsList, ok := data["comments"].([]interface{}); ok {
for _, item := range commentsList {
if comment, ok := item.(map[string]interface{}); ok {
comments = append(comments, comment)
}
}
}
// 计算分页
totalComments := len(comments)
startIdx := (page - 1) * pageSize
endIdx := startIdx + pageSize
if endIdx > totalComments {
endIdx = totalComments
}
// 获取当前页的评论
var pageComments []map[string]interface{}
if startIdx < totalComments {
pageComments = comments[startIdx:endIdx]
}
html.WriteString(` <div id="comment-list">
`)
if len(pageComments) == 0 {
html.WriteString(` <div class="empty">暂无评论</div>`)
} else {
for idx, comment := range pageComments {
info := parseCommentData(comment)
// 生成 HTML
html.WriteString(` <div class="comment-item" id="comment-`)
html.WriteString(strconv.Itoa(idx))
html.WriteString(`">
<div class="user-info">
<img src="`)
html.WriteString(htmlEscape(info.UserAvatar))
html.WriteString(`" class="user-avatar" alt="`)
html.WriteString(htmlEscape(info.UserName))
html.WriteString(`的头像" onerror="this.style.display='none'" loading="lazy">
<div class="user-name">`)
html.WriteString(htmlEscape(info.UserName))
if info.IsAuthor {
html.WriteString(`<span class="author-badge">作者</span>`)
}
if info.StickerImageURL != "" {
html.WriteString(`<img src="`)
html.WriteString(htmlEscape(info.StickerImageURL))
html.WriteString(`" class="user-sticker" alt="勋章">`)
}
html.WriteString(`</div>
</div>
<div class="comment-content">`)
html.WriteString(replaceEmojiWithImages(htmlEscape(info.CommentText)))
html.WriteString(`</div>
`)
if info.ImageURL != "" {
html.WriteString(` <img src="`)
html.WriteString(htmlEscape(info.ImageURL))
html.WriteString(`" class="comment-img" alt="评论图片" onclick="showImage('`)
html.WriteString(htmlEscape(info.ImageLargeURL))
html.WriteString(`')" onerror="this.style.display='none'" loading="lazy">
`)
}
html.WriteString(` <div class="comment-time">`)
html.WriteString(info.CreateTime)
html.WriteString(`</div>
<div class="comment-meta">
<span><i class="far fa-heart"></i>`)
html.WriteString(strconv.Itoa(info.DiggCount))
html.WriteString(`</span>
<span class="reply-btn" onclick="loadReplies(`)
html.WriteString(strconv.Itoa(idx))
html.WriteString(`, '`)
html.WriteString(htmlEscape(info.CommentID))
html.WriteString(`', `)
html.WriteString(strconv.Itoa(info.ReplyCount))
html.WriteString(`)"><i class="far fa-comment-dots"></i>`)
html.WriteString(strconv.Itoa(info.ReplyCount))
html.WriteString(`</span>
</div>
<div class="replies-container" id="replies-`)
html.WriteString(strconv.Itoa(idx))
html.WriteString(`"></div>
</div>
`)
}
}
// 如果初始加载就没有更多数据了,显示提示
if !hasMore && len(pageComments) > 0 {
html.WriteString(`
<div class="empty">没有更多评论了</div>`)
}
html.WriteString(`
</div>
<div class="image-viewer" id="imageViewer">
<span class="close-btn" onclick="closeImage()">&times;</span>
<img id="previewImage" src="" alt="图片预览">
</div>
<div class="back-to-top" id="backToTop" onclick="scrollToTop()">
<i class="fas fa-arrow-up"></i>
</div>
<script>
const itemID = '`)
html.WriteString(itemID)
html.WriteString(`';
const bookID = '`)
html.WriteString(bookID)
html.WriteString(`';
const para = `)
html.WriteString(strconv.Itoa(para))
html.WriteString(`;
let currentSort = `)
html.WriteString(strconv.Itoa(sort))
html.WriteString(`;
const commentList = document.getElementById('comment-list');
const imageViewer = document.getElementById('imageViewer');
const backToTopBtn = document.getElementById('backToTop');
const LOADING_HTML = '<div class="loading"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>';
// 已加载回复的评论
const loadedReplies = new Set();
// URL 构建
function buildReviewURL(params) {
const baseParams = {
item_id: itemID,
book_id: bookID,
para: para
};
const query = new URLSearchParams({...baseParams, ...params});
return '/review?' + query.toString();
}
// 时间格式化
function formatTime(timestamp, format = 'simple') {
const date = new Date(timestamp * 1000);
if (format === 'full') {
return date.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit'
}).replace(/\//g, '-');
}
return date.toLocaleString('zh-CN');
}
// 图片渲染
function renderImage(imageData, type = 'comment') {
if (!imageData?.[0]) return '';
const imgUrl = imageData[0].expand_web_url || imageData[0].web_uri || '';
if (!imgUrl) return '';
const escapedUrl = escapeHtml(imgUrl);
if (type === 'reply') {
return '<img src="' + escapedUrl + '" class="comment-img" alt="回复图片" onclick="showImage(\'' + escapedUrl + '\')" onerror="this.style.display=\'none\'" style="max-width:200px;margin-top:5px;border-radius:4px;cursor:pointer;" loading="lazy">';
}
const largeUrl = escapeHtml(imageData[0].expand_web_url || imgUrl);
return '<img src="' + escapedUrl + '" class="comment-img" alt="评论图片" onclick="showImage(\'' + largeUrl + '\')" onerror="this.style.display=\'none\'" loading="lazy">';
}
// 防抖
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 滚动信息获取
function getScrollInfo() {
const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
const scrollHeight = document.documentElement.scrollHeight;
const clientHeight = document.documentElement.clientHeight;
return {
scrollTop,
scrollHeight,
clientHeight,
distanceFromBottom: scrollHeight - (scrollTop + clientHeight)
};
}
// 切换排序
async function switchSort(newSort) {
if (currentSort === newSort) return;
document.querySelectorAll('.sort-tab').forEach(tab => tab.classList.remove('active'));
event.target.closest('.sort-tab').classList.add('active');
commentList.innerHTML = LOADING_HTML;
try {
currentSort = newSort;
currentOffset = 0;
const url = buildReviewURL({ offset: 0, count: 20, sort: newSort });
const response = await fetch(url);
const result = await response.json();
if (result.code === 0 && result.data && result.data.comments) {
hasMore = result.data.has_more || false;
currentOffset = result.data.next_offset || 0;
const comments = result.data.comments || [];
if (comments.length === 0) {
commentList.innerHTML = '<div class="empty">暂无评论</div>';
commentIndex = 0;
} else {
commentList.innerHTML = comments.map((comment, idx) => renderComment(comment, idx)).join('');
commentIndex = comments.length;
// 如果没有更多数据,显示提示
if (!hasMore) {
commentList.insertAdjacentHTML('beforeend', '<div class="empty">没有更多评论了</div>');
}
}
loadedReplies.clear();
window.scrollTo({ top: 0, behavior: 'smooth' });
} else {
commentList.innerHTML = '<div class="empty">加载失败,请重试</div>';
commentIndex = 0;
}
} catch (error) {
console.error('切换排序失败:', error);
commentList.innerHTML = '<div class="empty">加载失败,请重试</div>';
}
}
// 加载回复
async function loadReplies(idx, commentID, count) {
const container = document.getElementById('replies-' + idx);
if (count === 0) {
if (container.classList.contains('show')) {
container.classList.remove('show');
return;
}
container.innerHTML = '<div class="loading" style="color: #999;">暂无回复</div>';
container.classList.add('show');
loadedReplies.add(commentID);
return;
}
if (loadedReplies.has(commentID)) {
container.classList.toggle('show');
return;
}
container.innerHTML = LOADING_HTML;
container.classList.add('show');
try {
const url = buildReviewURL({ comment_id: commentID, offset: 0, count: 20 });
const response = await fetch(url);
const result = await response.json();
if (result.code !== 0 || !result.data) {
container.innerHTML = '<div class="loading">暂无回复</div>';
return;
}
const replies = result.data.reply_list || [];
const totalCount = result.data.count || replies.length;
const hasMore = result.data.has_more || false;
const nextOffset = result.data.next_offset || 0;
if (replies.length === 0) {
container.innerHTML = '<div class="loading">暂无回复</div>';
return;
}
let html = replies.map(renderReply).join('');
if (hasMore) {
html += '<div class="load-more-replies" style="text-align:center;padding:10px;color:var(--text-secondary);cursor:pointer;" ' +
'onclick="loadMoreReplies(\'' + escapeHtml(commentID) + '\', ' + nextOffset + ', this)">' +
'<i class="fas fa-angle-down"></i> 加载更多回复 (还有 ' + (totalCount - replies.length) + ' 条)' +
'</div>';
}
container.innerHTML = html;
loadedReplies.add(commentID);
} catch (error) {
console.error('加载回复失败:', error);
container.innerHTML = '<div class="loading">加载失败</div>';
}
}
// 加载更多回复
async function loadMoreReplies(commentID, offset, button) {
button.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 加载中...';
try {
const url = buildReviewURL({ comment_id: commentID, offset: offset, count: 20 });
const response = await fetch(url);
const result = await response.json();
if (result.code !== 0 || !result.data) {
button.textContent = '加载失败';
return;
}
const replies = result.data.reply_list || [];
const totalCount = result.data.count || 0;
const hasMore = result.data.has_more || false;
const nextOffset = result.data.next_offset || 0;
button.insertAdjacentHTML('beforebegin', replies.map(renderReply).join(''));
if (hasMore) {
const loadedCount = offset + replies.length;
button.innerHTML = '<i class="fas fa-angle-down"></i> 加载更多回复 (还有 ' + (totalCount - loadedCount) + ' 条)';
button.onclick = () => loadMoreReplies(commentID, nextOffset, button);
} else {
button.remove();
}
} catch (error) {
console.error('加载更多回复失败:', error);
button.textContent = '加载失败,点击重试';
}
}
// HTML 转义
const htmlEscapeMap = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
};
function escapeHtml(text) {
return text.replace(/[&<>"']/g, m => htmlEscapeMap[m]);
}
// 表情替换
const emojiMap = ` + generateEmojiMapJS() + `;
const emojiPattern = new RegExp(
Object.keys(emojiMap)
.map(e => e.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
.join('|'),
'g'
);
function replaceEmoji(text) {
return text.replace(emojiPattern, match =>
'<img src="' + emojiMap[match] + '" class="emoji-img" alt="' + match + '" title="' + match + '" loading="lazy">'
);
}
// 渲染单个回复
function renderReply(reply) {
const userName = reply.user_info?.user_name || '匿名用户';
const userAvatar = reply.user_info?.user_avatar || '';
const text = reply.text || '';
const time = formatTime(reply.create_timestamp || 0);
const imageHTML = renderImage(reply.image_data, 'reply');
return '<div class="reply-item">' +
'<img src="' + escapeHtml(userAvatar) + '" class="reply-avatar" alt="' + escapeHtml(userName) + '的头像" onerror="this.style.display=\'none\';" loading="lazy">' +
'<div class="reply-content">' +
'<span class="reply-username">' + escapeHtml(userName) + '</span>' +
'<div class="reply-text">' + replaceEmoji(escapeHtml(text)) + imageHTML + '</div>' +
'<div class="reply-time">' + time + '</div>' +
'</div>' +
'</div>';
}
// 渲染单个评论
function renderComment(comment, idx) {
const userName = comment.user_info?.user_name || '匿名用户';
const userAvatar = comment.user_info?.user_avatar || '';
const isAuthor = comment.user_info?.is_author || false;
const commentText = comment.text || '';
const commentID = comment.comment_id || '';
const diggCount = comment.digg_count || 0;
const replyCount = comment.reply_count || 0;
const createTime = formatTime(comment.create_timestamp || 0, 'full');
const imageHTML = renderImage(comment.image_data);
return '<div class="comment-item" id="comment-' + idx + '">' +
'<div class="user-info">' +
'<img src="' + escapeHtml(userAvatar) + '" class="user-avatar" alt="' + escapeHtml(userName) + '的头像" onerror="this.style.display=\'none\'" loading="lazy">' +
'<div class="user-name">' + escapeHtml(userName) +
(isAuthor ? '<span class="author-badge">作者</span>' : '') +
'</div></div>' +
'<div class="comment-content">' + replaceEmoji(escapeHtml(commentText)) + '</div>' +
imageHTML +
'<div class="comment-time">' + createTime + '</div>' +
'<div class="comment-meta">' +
'<span><i class="far fa-heart"></i>' + diggCount + '</span>' +
'<span class="reply-btn" onclick="loadReplies(' + idx + ', \'' + escapeHtml(commentID) + '\', ' + replyCount + ')">' +
'<i class="far fa-comment-dots"></i>' + replyCount + '</span>' +
'</div>' +
'<div class="replies-container" id="replies-' + idx + '"></div>' +
'</div>';
}
// 显示图片
function showImage(url) {
document.getElementById('previewImage').src = url;
imageViewer.classList.add('show');
document.body.style.overflow = 'hidden';
}
// 关闭图片
function closeImage() {
imageViewer.classList.remove('show');
document.body.style.overflow = '';
}
// 点击空白处关闭
imageViewer.addEventListener('click', e => {
if (e.target.id === 'imageViewer') closeImage();
});
// ESC 键关闭
document.addEventListener('keydown', e => {
if (e.key === 'Escape') closeImage();
});
// 懒加载相关变量
let currentOffset = `)
html.WriteString(strconv.Itoa(nextOffset))
html.WriteString(`;
const pageSize = `)
html.WriteString(strconv.Itoa(pageSize))
html.WriteString(`;
let hasMore = `)
if hasMore {
html.WriteString(`true`)
} else {
html.WriteString(`false`)
}
html.WriteString(`;
let isLoading = false;
let commentIndex = `)
html.WriteString(strconv.Itoa(len(pageComments)))
html.WriteString(`;
// 懒加载更多评论
async function loadMoreComments() {
if (isLoading || !hasMore) return;
isLoading = true;
let loadingDiv = document.getElementById('loading-indicator');
if (!loadingDiv) {
loadingDiv = document.createElement('div');
loadingDiv.id = 'loading-indicator';
loadingDiv.className = 'loading';
loadingDiv.innerHTML = LOADING_HTML;
commentList.appendChild(loadingDiv);
}
loadingDiv.style.display = 'block';
try {
const url = buildReviewURL({ offset: currentOffset, count: pageSize, sort: currentSort });
const response = await fetch(url);
const result = await response.json();
if (result.code === 0 && result.data) {
const comments = result.data.comments || [];
if (comments.length > 0) {
loadingDiv?.remove();
hasMore = result.data.has_more === true;
currentOffset = result.data.next_offset || 0;
comments.forEach((comment, idx) => {
commentList.insertAdjacentHTML('beforeend', renderComment(comment, commentIndex + idx));
});
commentIndex += comments.length;
if (!hasMore) {
commentList.insertAdjacentHTML('beforeend', '<div class="empty">没有更多评论了</div>');
}
} else {
loadingDiv.className = 'empty';
loadingDiv.textContent = '没有更多评论了';
hasMore = false;
}
} else {
loadingDiv.className = 'empty';
loadingDiv.textContent = '没有更多评论了';
hasMore = false;
}
} catch (error) {
console.error('加载失败:', error);
if (loadingDiv) {
loadingDiv.textContent = '加载失败';
setTimeout(() => loadingDiv.remove(), 2000);
}
} finally {
isLoading = false;
}
}
// 回到顶部
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
}
// 滚动监听
const handleScroll = debounce(() => {
const scroll = getScrollInfo();
// 显示/隐藏回到顶部按钮
backToTopBtn.classList.toggle('show', scroll.scrollTop > 300);
// 距离底部 200px 时触发加载
if (scroll.distanceFromBottom <= 200) {
loadMoreComments();
}
}, 100);
window.addEventListener('scroll', handleScroll, { passive: true });
</script>
</body>
</html>`)
return html.String()
}
// htmlEscape HTML 转义
func htmlEscape(s string) string {
s = strings.ReplaceAll(s, "&", "&amp;")
s = strings.ReplaceAll(s, "<", "&lt;")
s = strings.ReplaceAll(s, ">", "&gt;")
s = strings.ReplaceAll(s, "\"", "&quot;")
s = strings.ReplaceAll(s, "'", "&#39;")
return s
}
// generateEmojiMapJS 生成 JavaScript 格式的表情映射
func generateEmojiMapJS() string {
em := fqapi.GetEmojiManager()
emojiMap := em.GetAllEmojis()
var sb strings.Builder
sb.WriteString("{")
first := true
for emoji, url := range emojiMap {
if !first {
sb.WriteString(",")
}
first = false
// 转义特殊字符
escapedEmoji := strings.ReplaceAll(emoji, "\\", "\\\\")
escapedEmoji = strings.ReplaceAll(escapedEmoji, "'", "\\'")
escapedURL := strings.ReplaceAll(url, "\\", "\\\\")
escapedURL = strings.ReplaceAll(escapedURL, "'", "\\'")
sb.WriteString(fmt.Sprintf("'%s':'%s'", escapedEmoji, escapedURL))
}
sb.WriteString("}")
return sb.String()
}
// respondJSON 响应 JSON
func respondJSON(w http.ResponseWriter, statusCode int, data interface{}) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(data)
}