package main

import (
	"log"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var (
	upgrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

func main() {
	r := gin.Default()

	r.GET("/ws", func(c *gin.Context) {
		conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
		if err != nil {
			log.Println("Failed to upgrade to WebSocket:", err)
			return
		}

		// 处理心跳包
		go handleHeartbeat(conn)

		// 接收和处理客户端的消息
		for {
			_, msg, err := conn.ReadMessage()
			if err != nil {
				log.Println("Failed to read message from client:", err)
				break
			}
			log.Println("Received message from client:", string(msg))
		}
	})

	r.Run(":8080")
}

func handleHeartbeat(conn *websocket.Conn) {
	// 每隔一段时间向客户端发送心跳包
	ticker := time.NewTicker(5 * time.Second)
	defer ticker.Stop()

	for range ticker.C {
		err := conn.WriteMessage(websocket.TextMessage, []byte("heartbeat"))
		if err != nil {
			log.Println("Failed to send heartbeat:", err)
			break
		}
		log.Println("Sent heartbeat to client")
	}

	conn.Close()
}
