package controllers

import (
	"github.com/civet148/log"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
)

var upgrader = websocket.Upgrader{
	// 解决跨域问题
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
} // use default options

func (m *Controller) WebSocketRequest(c *gin.Context) {
	log.Infof("websocket request %+v", c.Request)
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Errorf("websocket upgrade error [%s]", err)
		m.ErrorStatus(c, http.StatusBadRequest, err.Error())
		return
	}
	defer conn.Close()
	err = m.GatewayCore.WebSocketRelay(conn)
	if err != nil {
		log.Warnf("websocket from [%s] relay closed with error [%s]", m.GetClientIP(c), err.Error())
	}
}
