handler.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package websocket
  2. import (
  3. "log"
  4. "net/http"
  5. "strconv"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gorilla/websocket"
  8. )
  9. var upgrader = websocket.Upgrader{
  10. ReadBufferSize: 1024,
  11. WriteBufferSize: 1024,
  12. // 允许跨域连接
  13. CheckOrigin: func(r *http.Request) bool {
  14. return true
  15. },
  16. }
  17. // HandleWebSocket 处理 WebSocket 连接
  18. func HandleWebSocket(hub *Hub) gin.HandlerFunc {
  19. return func(c *gin.Context) {
  20. // 从查询参数获取对话ID
  21. conversationIDStr := c.Query("conversation_id")
  22. if conversationIDStr == "" {
  23. c.JSON(http.StatusBadRequest, gin.H{"error": "conversation_id 不能为空"})
  24. return
  25. }
  26. conversationID, err := strconv.ParseUint(conversationIDStr, 10, 32)
  27. if err != nil {
  28. c.JSON(http.StatusBadRequest, gin.H{"error": "无效的 conversation_id"})
  29. return
  30. }
  31. // 从查询参数获取是否是访客(默认为 true,因为默认是访客连接)
  32. isVisitorStr := c.DefaultQuery("is_visitor", "true")
  33. isVisitor := isVisitorStr == "true" || isVisitorStr == "1"
  34. // 从查询参数获取客服ID(如果是客服连接,需要传递 agent_id)
  35. var agentID uint
  36. if !isVisitor {
  37. agentIDStr := c.Query("agent_id")
  38. if agentIDStr != "" {
  39. if parsed, err := strconv.ParseUint(agentIDStr, 10, 32); err == nil {
  40. agentID = uint(parsed)
  41. }
  42. }
  43. }
  44. // 升级 HTTP 连接为 WebSocket 连接
  45. conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
  46. if err != nil {
  47. log.Printf("WebSocket 升级失败: %v", err)
  48. return
  49. }
  50. // 创建客户端
  51. client := NewClient(hub, conn, uint(conversationID), isVisitor, agentID)
  52. // 注册客户端到 Hub
  53. client.hub.register <- client
  54. // 启动两个 goroutine:
  55. // 1. ReadPump:从客户端读取消息(主要是心跳包)
  56. // 2. WritePump:向客户端发送消息
  57. go client.WritePump()
  58. go client.ReadPump()
  59. log.Printf("✅ WebSocket 连接已建立: 对话ID=%d, 是访客=%v", conversationID, isVisitor)
  60. }
  61. }