Clean backend debug logging and standardize error reporting.

This removes verbose trace output in handlers/services and keeps only actionable error-level logs.
This commit is contained in:
2026-03-09 22:18:53 +08:00
parent 4d8f2ec997
commit 4c0177149a
13 changed files with 8 additions and 163 deletions

View File

@@ -2,7 +2,6 @@ package handler
import (
"context"
"fmt"
"strconv"
"github.com/gin-gonic/gin"
@@ -145,14 +144,11 @@ func (h *MessageHandler) GetConversationByID(c *gin.Context) {
}
conversationIDStr := c.Param("id")
fmt.Printf("[DEBUG] GetConversationByID: conversationIDStr = %s\n", conversationIDStr)
conversationID, err := service.ParseConversationID(conversationIDStr)
if err != nil {
fmt.Printf("[DEBUG] GetConversationByID: failed to parse conversation ID: %v\n", err)
response.BadRequest(c, "invalid conversation id")
return
}
fmt.Printf("[DEBUG] GetConversationByID: conversationID = %s\n", conversationID)
conv, err := h.chatService.GetConversationByID(c.Request.Context(), conversationID, userID)
if err != nil {
@@ -281,14 +277,11 @@ func (h *MessageHandler) SendMessage(c *gin.Context) {
}
conversationIDStr := c.Param("id")
fmt.Printf("[DEBUG] SendMessage: conversationIDStr = %s\n", conversationIDStr)
conversationID, err := service.ParseConversationID(conversationIDStr)
if err != nil {
fmt.Printf("[DEBUG] SendMessage: failed to parse conversation ID: %v\n", err)
response.BadRequest(c, "invalid conversation id")
return
}
fmt.Printf("[DEBUG] SendMessage: conversationID = %s, userID = %s\n", conversationID, userID)
var req dto.SendMessageRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -507,11 +500,8 @@ func (h *MessageHandler) MarkAsRead(c *gin.Context) {
// GET /api/conversations/unread/count
func (h *MessageHandler) GetUnreadCount(c *gin.Context) {
userID := c.GetString("user_id")
// 添加调试日志
fmt.Printf("[DEBUG] GetUnreadCount: user_id from context = %q\n", userID)
if userID == "" {
fmt.Printf("[DEBUG] GetUnreadCount: user_id is empty, returning 401\n")
response.Unauthorized(c, "")
return
}

View File

@@ -80,16 +80,10 @@ func (h *PostHandler) GetByID(c *gin.Context) {
// 注意:不再自动增加浏览量,浏览量通过 RecordView 端点单独记录
// 获取当前用户ID用于判断点赞和收藏状态
fmt.Printf("[DEBUG] GetByID - postID: %s, currentUserID: %s\n", id, currentUserID)
var isLiked, isFavorited bool
if currentUserID != "" {
isLiked = h.postService.IsLiked(c.Request.Context(), id, currentUserID)
isFavorited = h.postService.IsFavorited(c.Request.Context(), id, currentUserID)
fmt.Printf("[DEBUG] GetByID - isLiked: %v, isFavorited: %v\n", isLiked, isFavorited)
} else {
fmt.Printf("[DEBUG] GetByID - user not logged in, isLiked: false, isFavorited: false\n")
}
// 如果有当前用户,检查与帖子作者的相互关注状态
@@ -142,7 +136,7 @@ func (h *PostHandler) RecordView(c *gin.Context) {
// 增加浏览量
if err := h.postService.IncrementViews(c.Request.Context(), id, userID); err != nil {
fmt.Printf("[DEBUG] Failed to increment views for post %s: %v\n", id, err)
fmt.Printf("[ERROR] Failed to increment views for post %s: %v\n", id, err)
response.InternalServerError(c, "failed to record view")
return
}
@@ -192,8 +186,6 @@ func (h *PostHandler) List(c *gin.Context) {
return
}
fmt.Printf("[DEBUG] List - tab: %s, currentUserID: %s, posts count: %d\n", tab, currentUserID, len(posts))
isLikedMap := make(map[string]bool)
isFavoritedMap := make(map[string]bool)
if currentUserID != "" {
@@ -202,10 +194,7 @@ func (h *PostHandler) List(c *gin.Context) {
isFavorited := h.postService.IsFavorited(c.Request.Context(), post.ID, currentUserID)
isLikedMap[post.ID] = isLiked
isFavoritedMap[post.ID] = isFavorited
fmt.Printf("[DEBUG] List - postID: %s, isLiked: %v, isFavorited: %v\n", post.ID, isLiked, isFavorited)
}
} else {
fmt.Printf("[DEBUG] List - user not logged in\n")
}
// 转换为响应结构
@@ -308,7 +297,6 @@ func (h *PostHandler) Like(c *gin.Context) {
}
id := c.Param("id")
fmt.Printf("[DEBUG] Like - postID: %s, userID: %s\n", id, userID)
err := h.postService.Like(c.Request.Context(), id, userID)
if err != nil {
@@ -325,7 +313,6 @@ func (h *PostHandler) Like(c *gin.Context) {
isLiked := h.postService.IsLiked(c.Request.Context(), id, userID)
isFavorited := h.postService.IsFavorited(c.Request.Context(), id, userID)
fmt.Printf("[DEBUG] Like - postID: %s, isLiked: %v, isFavorited: %v\n", id, isLiked, isFavorited)
response.Success(c, dto.ConvertPostToResponse(post, isLiked, isFavorited))
}
@@ -339,7 +326,6 @@ func (h *PostHandler) Unlike(c *gin.Context) {
}
id := c.Param("id")
fmt.Printf("[DEBUG] Unlike - postID: %s, userID: %s\n", id, userID)
err := h.postService.Unlike(c.Request.Context(), id, userID)
if err != nil {
@@ -356,7 +342,6 @@ func (h *PostHandler) Unlike(c *gin.Context) {
isLiked := h.postService.IsLiked(c.Request.Context(), id, userID)
isFavorited := h.postService.IsFavorited(c.Request.Context(), id, userID)
fmt.Printf("[DEBUG] Unlike - postID: %s, isLiked: %v, isFavorited: %v\n", id, isLiked, isFavorited)
response.Success(c, dto.ConvertPostToResponse(post, isLiked, isFavorited))
}
@@ -370,7 +355,6 @@ func (h *PostHandler) Favorite(c *gin.Context) {
}
id := c.Param("id")
fmt.Printf("[DEBUG] Favorite - postID: %s, userID: %s\n", id, userID)
err := h.postService.Favorite(c.Request.Context(), id, userID)
if err != nil {
@@ -387,7 +371,6 @@ func (h *PostHandler) Favorite(c *gin.Context) {
isLiked := h.postService.IsLiked(c.Request.Context(), id, userID)
isFavorited := h.postService.IsFavorited(c.Request.Context(), id, userID)
fmt.Printf("[DEBUG] Favorite - postID: %s, isLiked: %v, isFavorited: %v\n", id, isLiked, isFavorited)
response.Success(c, dto.ConvertPostToResponse(post, isLiked, isFavorited))
}
@@ -401,7 +384,6 @@ func (h *PostHandler) Unfavorite(c *gin.Context) {
}
id := c.Param("id")
fmt.Printf("[DEBUG] Unfavorite - postID: %s, userID: %s\n", id, userID)
err := h.postService.Unfavorite(c.Request.Context(), id, userID)
if err != nil {
@@ -418,7 +400,6 @@ func (h *PostHandler) Unfavorite(c *gin.Context) {
isLiked := h.postService.IsLiked(c.Request.Context(), id, userID)
isFavorited := h.postService.IsFavorited(c.Request.Context(), id, userID)
fmt.Printf("[DEBUG] Unfavorite - postID: %s, isLiked: %v, isFavorited: %v\n", id, isLiked, isFavorited)
response.Success(c, dto.ConvertPostToResponse(post, isLiked, isFavorited))
}

View File

@@ -1,7 +1,6 @@
package handler
import (
"fmt"
"strconv"
"github.com/gin-gonic/gin"
@@ -572,16 +571,12 @@ func (h *UserHandler) GetFollowersList(c *gin.Context) {
page := c.DefaultQuery("page", "1")
pageSize := c.DefaultQuery("page_size", "20")
fmt.Printf("[DEBUG] GetFollowersList: userID=%s, currentUserID=%s\n", userID, currentUserID)
users, err := h.userService.GetFollowersList(c.Request.Context(), userID, page, pageSize)
if err != nil {
response.InternalServerError(c, "failed to get followers list")
return
}
fmt.Printf("[DEBUG] GetFollowersList: found %d users\n", len(users))
// 如果已登录,获取双向关注状态和实时计算的帖子数量
var userResponses []*dto.UserResponse
if currentUserID != "" && len(users) > 0 {
@@ -589,7 +584,6 @@ func (h *UserHandler) GetFollowersList(c *gin.Context) {
for i, u := range users {
userIDs[i] = u.ID
}
fmt.Printf("[DEBUG] GetFollowersList: checking mutual follow status for userIDs=%v\n", userIDs)
statusMap, _ := h.userService.GetMutualFollowStatus(c.Request.Context(), currentUserID, userIDs)
postsCountMap, _ := h.userService.GetUserPostCountBatch(c.Request.Context(), userIDs)
userResponses = dto.ConvertUsersToResponseWithMutualFollowAndPostsCount(users, statusMap, postsCountMap)

View File

@@ -106,13 +106,6 @@ func (h *WebSocketHandler) HandleWebSocket(c *gin.Context) {
return
}
// 如果用户已在线,先注销旧连接
if h.wsManager.IsUserOnline(userID) {
log.Printf("[DEBUG] 用户 %s 已有在线连接,复用该连接", userID)
} else {
log.Printf("[DEBUG] 用户 %s 当前不在线,创建新连接", userID)
}
// 创建客户端
client := &ws.Client{
ID: userID,
@@ -129,7 +122,6 @@ func (h *WebSocketHandler) HandleWebSocket(c *gin.Context) {
go client.WritePump()
go h.handleMessages(client)
log.Printf("[DEBUG] WebSocket连接建立: userID=%s, 当前在线=%v", userID, h.wsManager.IsUserOnline(userID))
}
// handleMessages 处理客户端消息
@@ -233,8 +225,6 @@ func (h *WebSocketHandler) handleChatMessage(client *ws.Client, msg *ws.WSMessag
return
}
log.Printf("[DEBUG handleChatMessage] 完整data: %+v", data)
conversationIDStr, _ := data["conversationId"].(string)
if conversationIDStr == "" {
@@ -293,8 +283,6 @@ func (h *WebSocketHandler) handleChatMessage(client *ws.Client, msg *ws.WSMessag
})
if client.Send != nil {
msgBytes, _ := json.Marshal(metaAckMsg)
log.Printf("[DEBUG handleChatMessage] 私聊 ack 消息: %s", string(msgBytes))
log.Printf("[DEBUG handleChatMessage] message.Segments 类型: %T, 值: %+v", message.Segments, message.Segments)
client.Send <- msgBytes
}
}
@@ -507,9 +495,6 @@ func (h *WebSocketHandler) handleGroupMessage(client *ws.Client, msg *ws.WSMessa
// 发送确认消息给发送者作为meta事件
// 使用 meta 事件格式发送 ack
log.Printf("[DEBUG HandleGroupMessageSend] 准备发送 ack 消息, userID=%s, messageID=%s, seq=%d",
client.UserID, savedMessage.ID, savedMessage.Seq)
metaAckMsg := ws.CreateWSMessage("meta", map[string]interface{}{
"detail_type": ws.MetaDetailTypeAck,
"conversation_id": conversationID,
@@ -523,8 +508,6 @@ func (h *WebSocketHandler) handleGroupMessage(client *ws.Client, msg *ws.WSMessa
})
if client.Send != nil {
msgBytes, _ := json.Marshal(metaAckMsg)
log.Printf("[DEBUG HandleGroupMessageSend] 发送 ack 消息到 channel, userID=%s, msg=%s",
client.UserID, string(msgBytes))
client.Send <- msgBytes
} else {
log.Printf("[ERROR HandleGroupMessageSend] client.Send 为 nil, userID=%s", client.UserID)

View File

@@ -1,7 +1,6 @@
package middleware
import (
"fmt"
"strings"
"github.com/gin-gonic/gin"
@@ -14,10 +13,8 @@ import (
func Auth(jwtService *service.JWTService) gin.HandlerFunc {
return func(c *gin.Context) {
authHeader := c.GetHeader("Authorization")
fmt.Printf("[DEBUG] Auth middleware: Authorization header = %q\n", authHeader)
if authHeader == "" {
fmt.Printf("[DEBUG] Auth middleware: no Authorization header, returning 401\n")
response.Unauthorized(c, "authorization header is required")
c.Abort()
return
@@ -26,26 +23,21 @@ func Auth(jwtService *service.JWTService) gin.HandlerFunc {
// 提取Token
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
fmt.Printf("[DEBUG] Auth middleware: invalid Authorization header format\n")
response.Unauthorized(c, "invalid authorization header format")
c.Abort()
return
}
token := parts[1]
fmt.Printf("[DEBUG] Auth middleware: token = %q\n", token[:min(20, len(token))]+"...")
// 验证Token
claims, err := jwtService.ParseToken(token)
if err != nil {
fmt.Printf("[DEBUG] Auth middleware: failed to parse token: %v\n", err)
response.Unauthorized(c, "invalid token")
c.Abort()
return
}
fmt.Printf("[DEBUG] Auth middleware: parsed claims, user_id = %q, username = %q\n", claims.UserID, claims.Username)
// 将用户信息存入上下文
c.Set("user_id", claims.UserID)
c.Set("username", claims.Username)
@@ -54,13 +46,6 @@ func Auth(jwtService *service.JWTService) gin.HandlerFunc {
}
}
func min(a, b int) int {
if a < b {
return a
}
return b
}
// OptionalAuth 可选认证中间件
func OptionalAuth(jwtService *service.JWTService) gin.HandlerFunc {
return func(c *gin.Context) {

View File

@@ -293,7 +293,6 @@ func (m *WebSocketManager) IsUserOnline(userID string) bool {
m.mutex.RLock()
defer m.mutex.RUnlock()
_, ok := m.clients[userID]
log.Printf("[DEBUG IsUserOnline] 检查用户 %s, 结果=%v, 当前在线用户=%v", userID, ok, m.clients)
return ok
}
@@ -305,9 +304,6 @@ func (m *WebSocketManager) sendMessage(broadcast *BroadcastMessage) {
return
}
log.Printf("[DEBUG WebSocket] sendMessage: 目标用户=%s, 当前在线用户数=%d, 消息类型=%s",
broadcast.TargetUser, len(m.clients), broadcast.Message.Type)
m.mutex.RLock()
defer m.mutex.RUnlock()
@@ -324,7 +320,6 @@ func (m *WebSocketManager) sendMessage(broadcast *BroadcastMessage) {
select {
case client.Send <- msgBytes:
log.Printf("[DEBUG WebSocket] 成功发送消息到用户 %s, 消息类型=%s", userID, broadcast.Message.Type)
default:
log.Printf("Failed to send message to user %s: channel full", userID)
}

View File

@@ -2,7 +2,6 @@ package repository
import (
"carrot_bbs/internal/model"
"fmt"
"time"
"gorm.io/gorm"
@@ -40,8 +39,6 @@ func (r *MessageRepository) GetConversation(id string) (*model.Conversation, err
func (r *MessageRepository) GetOrCreatePrivateConversation(user1ID, user2ID string) (*model.Conversation, error) {
var conv model.Conversation
fmt.Printf("[DEBUG] GetOrCreatePrivateConversation: user1ID=%s, user2ID=%s\n", user1ID, user2ID)
// 查找两个用户共同参与的私聊会话
err := r.db.Table("conversations c").
Joins("INNER JOIN conversation_participants cp1 ON c.id = cp1.conversation_id AND cp1.user_id = ?", user1ID).
@@ -53,7 +50,6 @@ func (r *MessageRepository) GetOrCreatePrivateConversation(user1ID, user2ID stri
_ = r.db.Model(&model.ConversationParticipant{}).
Where("conversation_id = ? AND user_id IN ?", conv.ID, []string{user1ID, user2ID}).
Update("hidden_at", nil).Error
fmt.Printf("[DEBUG] GetOrCreatePrivateConversation: found existing conversation, ID=%s\n", conv.ID)
return &conv, nil
}
@@ -62,7 +58,6 @@ func (r *MessageRepository) GetOrCreatePrivateConversation(user1ID, user2ID stri
}
// 没找到会话,创建新会话
fmt.Printf("[DEBUG] GetOrCreatePrivateConversation: no existing conversation found, creating new one\n")
conv = model.Conversation{
Type: model.ConversationTypePrivate,
}
@@ -85,10 +80,6 @@ func (r *MessageRepository) GetOrCreatePrivateConversation(user1ID, user2ID stri
return nil
})
if err == nil {
fmt.Printf("[DEBUG] GetOrCreatePrivateConversation: created new conversation, ID=%s\n", conv.ID)
}
return &conv, err
}
@@ -153,20 +144,10 @@ func (r *MessageRepository) GetMessagesAfterSeq(conversationID string, afterSeq
// GetMessagesBeforeSeq 获取指定seq之前的历史消息用于下拉加载更多
func (r *MessageRepository) GetMessagesBeforeSeq(conversationID string, beforeSeq int64, limit int) ([]*model.Message, error) {
var messages []*model.Message
fmt.Printf("[DEBUG] GetMessagesBeforeSeq: conversationID=%s, beforeSeq=%d, limit=%d\n", conversationID, beforeSeq, limit)
err := r.db.Where("conversation_id = ? AND seq < ?", conversationID, beforeSeq).
Order("seq DESC"). // 降序获取最新消息在前
Limit(limit).
Find(&messages).Error
fmt.Printf("[DEBUG] GetMessagesBeforeSeq: found %d messages, seq range: ", len(messages))
for i, m := range messages {
if i < 5 || i >= len(messages)-2 {
fmt.Printf("%d ", m.Seq)
} else if i == 5 {
fmt.Printf("... ")
}
}
fmt.Println()
// 反转回正序
for i, j := 0, len(messages)-1; i < j; i, j = i+1, j-1 {
messages[i], messages[j] = messages[j], messages[i]

View File

@@ -2,7 +2,6 @@ package repository
import (
"carrot_bbs/internal/model"
"fmt"
"gorm.io/gorm"
"gorm.io/gorm/clause"
@@ -362,8 +361,6 @@ func (r *UserRepository) GetMutualFollowStatus(currentUserID string, targetUserI
return result, nil
}
fmt.Printf("[DEBUG] GetMutualFollowStatus: currentUserID=%s, targetUserIDs=%v\n", currentUserID, targetUserIDs)
// 初始化所有目标用户为未关注状态
for _, userID := range targetUserIDs {
result[userID] = [2]bool{false, false}
@@ -377,7 +374,6 @@ func (r *UserRepository) GetMutualFollowStatus(currentUserID string, targetUserI
if err != nil {
return nil, err
}
fmt.Printf("[DEBUG] GetMutualFollowStatus: currentUser follows these targets: %v\n", followingIDs)
for _, id := range followingIDs {
status := result[id]
status[0] = true
@@ -392,13 +388,11 @@ func (r *UserRepository) GetMutualFollowStatus(currentUserID string, targetUserI
if err != nil {
return nil, err
}
fmt.Printf("[DEBUG] GetMutualFollowStatus: these targets follow currentUser: %v\n", followerIDs)
for _, id := range followerIDs {
status := result[id]
status[1] = true
result[id] = status
}
fmt.Printf("[DEBUG] GetMutualFollowStatus: final result=%v\n", result)
return result, nil
}

View File

@@ -229,7 +229,6 @@ func (s *chatServiceImpl) SendMessage(ctx context.Context, senderID string, conv
}
// 发送消息给接收者
log.Printf("[DEBUG SendMessage] 私聊消息 segments 类型: %T, 值: %+v", message.Segments, message.Segments)
wsMsg := websocket.CreateWSMessage(websocket.MessageTypeMessage, websocket.ChatMessage{
ID: message.ID,
ConversationID: message.ConversationID,
@@ -250,15 +249,11 @@ func (s *chatServiceImpl) SendMessage(ctx context.Context, senderID string, conv
// 如果接收者在线,发送实时消息
if s.wsManager != nil {
isOnline := s.wsManager.IsUserOnline(p.UserID)
log.Printf("[DEBUG SendMessage] 接收者 UserID=%s, 在线状态=%v", p.UserID, isOnline)
if isOnline {
log.Printf("[DEBUG SendMessage] 发送WebSocket消息给 UserID=%s, 消息类型=%s", p.UserID, wsMsg.Type)
s.wsManager.SendToUser(p.UserID, wsMsg)
}
}
}
} else {
log.Printf("[DEBUG SendMessage] 获取参与者失败: %v", err)
}
_ = participant // 避免未使用变量警告

View File

@@ -137,7 +137,7 @@ func (s *CommentService) afterCommentPublished(userID, postID, commentID string,
if parentUserID != userID {
notifyErr := s.systemMessageService.SendReplyNotification(context.Background(), parentUserID, userID, postID, *parentID, commentID)
if notifyErr != nil {
fmt.Printf("[DEBUG] Error sending reply notification: %v\n", notifyErr)
log.Printf("[ERROR] Error sending reply notification: %v", notifyErr)
}
}
} else {
@@ -145,7 +145,7 @@ func (s *CommentService) afterCommentPublished(userID, postID, commentID string,
if postOwnerID != userID {
notifyErr := s.systemMessageService.SendCommentNotification(context.Background(), postOwnerID, userID, postID, commentID)
if notifyErr != nil {
fmt.Printf("[DEBUG] Error sending comment notification: %v\n", notifyErr)
log.Printf("[ERROR] Error sending comment notification: %v", notifyErr)
}
}
}
@@ -252,9 +252,7 @@ func (s *CommentService) Like(ctx context.Context, commentID, userID string) err
)
}
if notifyErr != nil {
fmt.Printf("[DEBUG] Error sending like notification: %v\n", notifyErr)
} else {
fmt.Printf("[DEBUG] Like notification sent successfully\n")
log.Printf("[ERROR] Error sending like notification: %v", notifyErr)
}
}()
}

View File

@@ -276,9 +276,7 @@ func (s *PostService) Like(ctx context.Context, postID, userID string) error {
go func() {
notifyErr := s.systemMessageService.SendLikeNotification(context.Background(), post.UserID, userID, postID)
if notifyErr != nil {
fmt.Printf("[DEBUG] Error sending like notification: %v\n", notifyErr)
} else {
fmt.Printf("[DEBUG] Like notification sent successfully\n")
log.Printf("[ERROR] Error sending like notification: %v", notifyErr)
}
}()
}
@@ -343,9 +341,7 @@ func (s *PostService) Favorite(ctx context.Context, postID, userID string) error
go func() {
notifyErr := s.systemMessageService.SendFavoriteNotification(context.Background(), post.UserID, userID, postID)
if notifyErr != nil {
fmt.Printf("[DEBUG] Error sending favorite notification: %v\n", notifyErr)
} else {
fmt.Printf("[DEBUG] Favorite notification sent successfully\n")
log.Printf("[ERROR] Error sending favorite notification: %v", notifyErr)
}
}()
}

View File

@@ -165,15 +165,11 @@ func (s *systemMessageServiceImpl) SendReplyNotification(ctx context.Context, us
// SendFollowNotification 发送关注通知
func (s *systemMessageServiceImpl) SendFollowNotification(ctx context.Context, userID string, operatorID string) error {
fmt.Printf("[DEBUG] SendFollowNotification: userID=%s, operatorID=%s\n", userID, operatorID)
// 获取操作者信息
actorName, avatarURL, err := s.getActorInfo(ctx, operatorID)
if err != nil {
fmt.Printf("[DEBUG] SendFollowNotification: getActorInfo error: %v\n", err)
return err
}
fmt.Printf("[DEBUG] SendFollowNotification: actorName=%s, avatarURL=%s\n", actorName, avatarURL)
extraData := &model.SystemNotificationExtra{
ActorIDStr: operatorID,
@@ -193,16 +189,8 @@ func (s *systemMessageServiceImpl) SendFollowNotification(ctx context.Context, u
return fmt.Errorf("failed to create follow notification: %w", err)
}
fmt.Printf("[DEBUG] SendFollowNotification: notification created, ID=%d, Content=%s\n", notification.ID, notification.Content)
// 推送通知
pushErr := s.pushService.PushSystemNotification(ctx, userID, notification)
if pushErr != nil {
fmt.Printf("[DEBUG] SendFollowNotification: PushSystemNotification error: %v\n", pushErr)
} else {
fmt.Printf("[DEBUG] SendFollowNotification: PushSystemNotification success\n")
}
return pushErr
return s.pushService.PushSystemNotification(ctx, userID, notification)
}
// SendFavoriteNotification 发送收藏通知
@@ -387,12 +375,9 @@ func (s *systemMessageServiceImpl) SendBroadcastAnnouncement(ctx context.Context
// createNotification 创建系统通知(存储到独立表)
func (s *systemMessageServiceImpl) createNotification(ctx context.Context, userID string, notifyType model.SystemNotificationType, content string, extraData *model.SystemNotificationExtra) (*model.SystemNotification, error) {
fmt.Printf("[DEBUG] createNotification: userID=%s, notifyType=%s\n", userID, notifyType)
// 生成雪花算法ID
id, err := utils.GetSnowflake().GenerateID()
if err != nil {
fmt.Printf("[DEBUG] createNotification: failed to generate ID: %v\n", err)
return nil, fmt.Errorf("failed to generate notification ID: %w", err)
}
@@ -405,18 +390,14 @@ func (s *systemMessageServiceImpl) createNotification(ctx context.Context, userI
IsRead: false,
}
fmt.Printf("[DEBUG] createNotification: notification created with ID=%d, ReceiverID=%s\n", id, userID)
// 保存通知到数据库
if err := s.notifyRepo.Create(notification); err != nil {
fmt.Printf("[DEBUG] createNotification: failed to save notification: %v\n", err)
return nil, fmt.Errorf("failed to save notification: %w", err)
}
// 失效系统消息未读数缓存
cache.InvalidateUnreadSystem(s.cache, userID)
fmt.Printf("[DEBUG] createNotification: notification saved successfully, ID=%d\n", notification.ID)
return notification, nil
}
@@ -426,7 +407,6 @@ func (s *systemMessageServiceImpl) getActorInfo(ctx context.Context, operatorID
if s.userRepo != nil {
user, err := s.userRepo.GetByID(operatorID)
if err != nil {
fmt.Printf("[DEBUG] getActorInfo: failed to get user %s: %v\n", operatorID, err)
return "用户", utils.GenerateDefaultAvatarURL("用户"), nil // 返回默认值,不阻断流程
}
avatar := utils.GetAvatarOrDefault(user.Username, user.Nickname, user.Avatar)

View File

@@ -306,8 +306,6 @@ func (s *UserService) GetFollowing(ctx context.Context, userID string, page, pag
// FollowUser 关注用户
func (s *UserService) FollowUser(ctx context.Context, followerID, followeeID string) error {
fmt.Printf("[DEBUG] FollowUser called: followerID=%s, followeeID=%s\n", followerID, followeeID)
blocked, err := s.userRepo.IsBlockedEitherDirection(followerID, followeeID)
if err != nil {
return err
@@ -319,11 +317,9 @@ func (s *UserService) FollowUser(ctx context.Context, followerID, followeeID str
// 检查是否已经关注
isFollowing, err := s.userRepo.IsFollowing(followerID, followeeID)
if err != nil {
fmt.Printf("[DEBUG] Error checking existing follow: %v\n", err)
return err
}
if isFollowing {
fmt.Printf("[DEBUG] Already following, skip creation\n")
return nil // 已经关注,直接返回成功
}
@@ -335,23 +331,18 @@ func (s *UserService) FollowUser(ctx context.Context, followerID, followeeID str
err = s.userRepo.CreateFollow(follow)
if err != nil {
fmt.Printf("[DEBUG] CreateFollow error: %v\n", err)
return err
}
fmt.Printf("[DEBUG] Follow record created successfully\n")
// 刷新关注者的关注数(通过实际计数,更可靠)
err = s.userRepo.RefreshFollowingCount(followerID)
if err != nil {
fmt.Printf("[DEBUG] Error refreshing following count: %v\n", err)
// 不回滚,计数可以通过其他方式修复
}
// 刷新被关注者的粉丝数(通过实际计数,更可靠)
err = s.userRepo.RefreshFollowersCount(followeeID)
if err != nil {
fmt.Printf("[DEBUG] Error refreshing followers count: %v\n", err)
// 不回滚,计数可以通过其他方式修复
}
@@ -359,56 +350,38 @@ func (s *UserService) FollowUser(ctx context.Context, followerID, followeeID str
if s.systemMessageService != nil {
// 异步发送通知,不阻塞主流程
go func() {
notifyErr := s.systemMessageService.SendFollowNotification(context.Background(), followeeID, followerID)
if notifyErr != nil {
fmt.Printf("[DEBUG] Error sending follow notification: %v\n", notifyErr)
} else {
fmt.Printf("[DEBUG] Follow notification sent successfully to %s\n", followeeID)
}
_ = s.systemMessageService.SendFollowNotification(context.Background(), followeeID, followerID)
}()
}
fmt.Printf("[DEBUG] FollowUser completed: followerID=%s, followeeID=%s\n", followerID, followeeID)
return nil
}
// UnfollowUser 取消关注用户
func (s *UserService) UnfollowUser(ctx context.Context, followerID, followeeID string) error {
fmt.Printf("[DEBUG] UnfollowUser called: followerID=%s, followeeID=%s\n", followerID, followeeID)
// 检查是否已经关注
isFollowing, err := s.userRepo.IsFollowing(followerID, followeeID)
if err != nil {
fmt.Printf("[DEBUG] Error checking existing follow: %v\n", err)
return err
}
if !isFollowing {
fmt.Printf("[DEBUG] Not following, skip deletion\n")
return nil // 没有关注,直接返回成功
}
// 删除关注关系
err = s.userRepo.DeleteFollow(followerID, followeeID)
if err != nil {
fmt.Printf("[DEBUG] DeleteFollow error: %v\n", err)
return err
}
fmt.Printf("[DEBUG] Follow record deleted successfully\n")
// 刷新关注者的关注数(通过实际计数,更可靠)
err = s.userRepo.RefreshFollowingCount(followerID)
if err != nil {
fmt.Printf("[DEBUG] Error refreshing following count: %v\n", err)
}
// 刷新被关注者的粉丝数(通过实际计数,更可靠)
err = s.userRepo.RefreshFollowersCount(followeeID)
if err != nil {
fmt.Printf("[DEBUG] Error refreshing followers count: %v\n", err)
}
fmt.Printf("[DEBUG] UnfollowUser completed: followerID=%s, followeeID=%s\n", followerID, followeeID)
return nil
}