package controllers

import (
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gorilla/websocket"
	"net/http"
	"time"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true // 允许跨域连接
	},
}

type WebSocketController struct {
	beego.Controller
}

func (c *WebSocketController) Connect() {
	ws, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
	if err != nil {
		//beego.Error(err)
		return
	}
	defer ws.Close()

	for {
		var msg string
		_, _, err := ws.ReadMessage()
		if err != nil {
			//	beego.Error(err)
			break
		}
		// 处理接收到的消息
		fmt.Printf("Received: %s\n", msg)

		// 发送消息回客户端
		err = ws.WriteMessage(websocket.TextMessage, []byte("Server: "+msg))
		if err != nil {
			//beego.Error(err)
			break
		}
		time.Sleep(time.Second) // 模拟延迟
	}
}
