Certainly! I've reviewed your code and can help refactor it to be more elegant and maintainable. Below, I'll provide a refactored version of your ChatHandler function and related functions, along with explanations of the changes made and how they improve the code.
Refactored Code
package handlers
import (
"context"
"encoding/json"
"errors"
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"go.mongodb.org/mongo-driver/bson/primitive"
"your_project/middleware"
"your_project/models"
"your_project/serializer"
"your_project/service"
"your_project/task"
"your_project/utils"
)
// ChatHandler handles the WebSocket connection and message processing
func ChatHandler(c *gin.Context) {
// Upgrade the HTTP connection to a WebSocket
conn, err := middleware.Upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
handleError(c, err)
return
}
defer conn.Close()
userID := c.GetString("userid")
sendToClientChan := make(chan []byte)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Start the message sender goroutine
go messageSender(ctx, conn, sendToClientChan)
// Initialize timers
inactivityTimer := time.NewTimer(10 * time.Minute)
remindTimer := time.NewTimer(50 * time.Second)
// Start the message receiver loop
for {
select {
case <-ctx.Done():
log.Println("Connection closed")
return
case <-inactivityTimer.C:
log.Println("User inactive for 10 minutes, closing connection")
return
case <-remindTimer.C:
log.Println("User inactive for 50 seconds, sending reminder")
sendToClientChan <- utils.NewTextMessage("你还在吗?", "")
remindTimer.Reset(50 * time.Second)
default:
// Handle incoming messages
err := handleMessage(ctx, conn, sendToClientChan, userID)
if err != nil {
log.Println("Error handling message:", err)
return
}
// Reset timers upon successful message handling
resetTimer(inactivityTimer, 10*time.Minute)
resetTimer(remindTimer, 50*time.Second)
}
}
}
func handleError(c *gin.Context, err error) {
c.JSON(http.StatusOK, serializer.WsResponse(err.Error(), 1, "aiSaid", nil))
}
func messageSender(ctx context.Context, conn *websocket.Conn, sendToClientChan <-chan []byte) {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
log.Println("Message sender goroutine started")
for {
select {
case <-ctx.Done():
log.Println("Message sender goroutine exiting")
return
case msg := <-sendToClientChan:
if err := conn.WriteMessage(websocket.TextMessage, msg); err != nil {
log.Println("Error writing message:", err)
return
}
case <-ticker.C:
if err := conn.WriteMessage(websocket.PingMessage, nil); err != nil {
log.Println("Error sending ping:", err)
return
}
}
}
}
func resetTimer(t *time.Timer, duration time.Duration) {
if !t.Stop() {
select {
case <-t.C:
default:
}
}
t.Reset(duration)
}
func handleMessage(ctx context.Context, conn *websocket.Conn, sendToClientChan chan<- []byte, userID string) error {
_, message, err := conn.ReadMessage()
if err != nil {
log.Println("Failed to read message:", err)
sendToClientChan <- utils.NewTextMessage("不好意思,希文没听清你说什么。你能再说一遍吗?", "")
return nil
}
log.Println("Received message:", string(message))
var chatBody models.UserChatReq
if err := json.Unmarshal(message, &chatBody); err != nil {
log.Println("Failed to parse message:", err)
sendToClientChan <- utils.NewTextMessage("不好意思,希文没理解你的意思。你能再说一遍吗?", "")
return nil
}
conv := task.GetConversation(userID)
if conv == nil {
log.Println("Failed to get conversation")
sendToClientChan <- utils.NewTextMessage("不好意思,希文太忙了,忘了和你聊过啥了。你能再说一遍吗?", "")
return nil
}
conv.SendToClientChan = sendToClientChan
userIDObj, _ := primitive.ObjectIDFromHex(userID)
// Process the message based on WApi
switch chatBody.WApi {
case "userSaid":
err = handleUserSaid(ctx, conv, chatBody, userIDObj)
case "xObjSubmitReq":
err = handleXObjSubmitReq(conv, chatBody)
default:
sendErrorResponse(sendToClientChan, "未知的路由")
err = errors.New("未知的路由")
}
return err
}
func handleUserSaid(ctx context.Context, conv *task.Conversation, chatBody models.UserChatReq, userIDObj primitive.ObjectID) error {
if chatBody.Data.TaskID == "" {
// Start a new task
return startNewTask(conv, userIDObj)
}
// Continue an existing task
activeTask := task.GetTaskByID(chatBody.Data.TaskID)
if activeTask == nil || (activeTask.GetTaskType() != task.AI && activeTask.GetTaskType() != task.Eva) {
sendErrorResponse(conv.SendToClientChan, "任务ID与路由不匹配")
return errors.New("任务ID与路由不匹配")
}
conv.ActiveTask = activeTask
return runActiveTask(conv, chatBody.Data)
}
func handleXObjSubmitReq(conv *task.Conversation, chatBody models.UserChatReq) error {
if chatBody.Data.TaskID == "" {
sendErrorResponse(conv.SendToClientChan, "任务ID与路由不匹配,xObjSubmit 不应该由用户初始化")
return errors.New("unknown taskID expect one")
}
activeTask := task.GetTaskByID(chatBody.Data.TaskID)
if activeTask == nil || activeTask.GetTaskType() != task.Question {
sendErrorResponse(conv.SendToClientChan, "任务ID与路由不匹配")
return errors.New("任务ID与路由不匹配")
}
conv.ActiveTask = activeTask
return runActiveTask(conv, chatBody.Data)
}
func startNewTask(conv *task.Conversation, userIDObj primitive.ObjectID) error {
summaryService := service.NewUserSummaryService(userIDObj)
var activeTask task.Task
// Determine if the user has performed the evaluation test before
hasTest := summaryService.HasEvaTest()
stuProfile := summaryService.GetStuProfile()
if hasTest {
activeTask = task.NewAITask("", stuProfile, 180, nil, userIDObj, models.STUDYTASK, conv)
} else {
activeTask, _ = task.NewEvaTask("小学生", 180, nil, userIDObj, conv)
}
conv.ActiveTask = activeTask
// Start the task in a goroutine
go func() {
activeTask.Init()
runActiveTask(conv, models.ChatData{})
}()
return nil
}
func runActiveTask(conv *task.Conversation, data models.ChatData) error {
conv.ActiveTask.UpdateTaskLastUserSaid()
doneChan := make(chan string)
// Run the task in a goroutine
go func() {
conv.ActiveTask.Run(doneChan, data)
}()
// Wait for the task to complete
result := <-doneChan
switch result {
case "done":
conv.SwitchTask(conv.UserID)
case "continue":
// Task continues, no action needed
default:
log.Println("Task failed:", result)
sendErrorResponse(conv.SendToClientChan, result)
return errors.New(result)
}
return nil
}
func sendErrorResponse(sendToClientChan chan<- []byte, message string) {
resByte, _ := json.Marshal(serializer.WsResponse(message, 1, "aiSaid", nil))
sendToClientChan <- resByte
}
Explanation of Changes
-
Simplified Goroutine Management:
- Removed the nested goroutine in
handleMessage that was potentially causing goroutine leaks.
- Instead of starting a goroutine every time
handleMessage is called, we start a goroutine only when necessary (e.g., when starting a new task).
- We ensure that goroutines are properly managed and that there are no leaks by using context cancellation and proper synchronization.
-
Context Usage:
- Enhanced the use of
context.Context to manage cancellation and timeouts effectively.
- Passing
ctx down to functions that require it, allowing for better control over goroutine lifecycles.
-
Improved Timer Handling:
- Created a helper function
resetTimer to reset timers cleanly without race conditions.
- Ensured timers are properly stopped and reset to prevent unexpected behavior.
-
Error Handling and Logging:
- Unified error responses using the
sendErrorResponse helper function.
- Improved logging messages to provide clearer information about errors and states.
- Returned errors where appropriate to allow the calling function to handle them.
-
Switch-Case for Message Handling:
- Replaced the if-else statements with a switch-case in
handleMessage for better readability and scalability.
- Each case in the switch statement delegates to a specific handler function (
handleUserSaid, handleXObjSubmitReq).
-
Task Management:
- Separated task starting and running into distinct functions (
startNewTask, runActiveTask) to clarify the flow.
- Used the conversation's
ActiveTask field directly without unnecessary reassignment.
-
Removed Unnecessary Channels:
- Eliminated the
destoryListen channel and associated complexity since the new structure doesn't require it.
- Streamlined communication between goroutines using channels already in use.
-
Added Comments and Cleaned Up Code:
- Added comments to explain the purpose of functions and major code blocks.
Benefits of Refactoring
- Readability: The refactored code is more organized, making it easier to understand the flow and logic.
- Maintainability: By modularizing the code and using helper functions, future updates and maintenance become simpler.
- Scalability: The use of switch-case statements and separate handler functions allows for easier addition of new message types or tasks.
- Reliability: Proper management of goroutines and contexts prevents resource leaks and ensures the application behaves as expected under various conditions.
- Performance: Eliminating unnecessary goroutines and channels can improve the performance and reduce the overhead of the application.
Additional Recommendations
- Error Handling: Consider defining custom error types or using error wrapping to provide more context when debugging.
- Validation: Add validation for user inputs (e.g., ensure
chatBody.Data has the expected fields).
- Logging: Enhance logging by including additional context information (e.g., user IDs, task IDs) and using structured logging if possible.
- Concurrency Safety: Ensure that shared resources within
task and conversation packages are protected using appropriate synchronization mechanisms (e.g., mutexes) if they are accessed by multiple goroutines.
Let me know if you have any questions or need further assistance with the refactored code!