后端 Go+Gin:认证/CSRF/限流、板块、帖子、评论、点赞、通知、用户资料、置顶推荐;前端 Next.js 16:发帖/编辑/删除、搜索、分页、点赞、通知中心、设置;基础设施 docker-compose 与配置模板;添加 .gitignore 与专有许可证(保留所有权利)
97 lines
2.5 KiB
Go
97 lines
2.5 KiB
Go
package handler
|
|
|
|
import (
|
|
"net/http"
|
|
"strconv"
|
|
|
|
"github.com/freefire/jiang13-bbs/middleware"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
// UserProfile 获取用户资料:基本信息 + 统计 + 发帖列表(分页)
|
|
func (h *Handlers) UserProfile(c *gin.Context) {
|
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户 ID"})
|
|
return
|
|
}
|
|
|
|
user, err := h.Auth.GetUserByID(uint(id))
|
|
if err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
|
|
return
|
|
}
|
|
|
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
|
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
|
|
|
posts, postsTotal, err := h.Post.ListByUser(user.ID, page, size)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
// 填充点赞状态(仅登录用户)
|
|
if claims := middleware.CurrentUser(c); claims != nil {
|
|
ids := make([]uint, 0, len(posts))
|
|
for _, p := range posts {
|
|
ids = append(ids, p.ID)
|
|
}
|
|
likedMap := h.Like.BatchHasLiked(ids, claims.ID)
|
|
for i := range posts {
|
|
posts[i].Liked = likedMap[posts[i].ID]
|
|
}
|
|
}
|
|
|
|
postCount, _ := h.Post.CountByUser(user.ID)
|
|
commentCount, _ := h.Comment.CountByUser(user.ID)
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"user": gin.H{
|
|
"id": user.ID,
|
|
"username": user.Username,
|
|
"nickname": user.Nickname,
|
|
"avatar": user.Avatar,
|
|
"role": user.Role,
|
|
"created_at": user.CreatedAt,
|
|
},
|
|
"stats": gin.H{
|
|
"post_count": postCount,
|
|
"comment_count": commentCount,
|
|
},
|
|
"posts": posts,
|
|
"posts_total": postsTotal,
|
|
"page": page,
|
|
"size": size,
|
|
})
|
|
}
|
|
|
|
// UserComments 获取用户发表的评论列表(分页,含帖子标题)
|
|
func (h *Handlers) UserComments(c *gin.Context) {
|
|
id, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
|
if err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的用户 ID"})
|
|
return
|
|
}
|
|
// 校验用户存在
|
|
if _, err := h.Auth.GetUserByID(uint(id)); err != nil {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
|
|
return
|
|
}
|
|
|
|
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
|
size, _ := strconv.Atoi(c.DefaultQuery("size", "20"))
|
|
|
|
comments, total, err := h.Comment.ListByUser(uint(id), page, size)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"comments": comments,
|
|
"total": total,
|
|
"page": page,
|
|
"size": size,
|
|
})
|
|
}
|