ws_controller.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package controllers
  2. import (
  3. logger "eta/eta_mini_ht_api/common/component/log"
  4. "fmt"
  5. beego "github.com/beego/beego/v2/server/web"
  6. "github.com/gorilla/websocket"
  7. "net/http"
  8. "time"
  9. )
  10. var upgrader = websocket.Upgrader{
  11. CheckOrigin: func(r *http.Request) bool {
  12. fmt.Println(r.Header.Get("Authorization"))
  13. return true // 允许跨域连接
  14. },
  15. }
  16. type WebSocketController struct {
  17. beego.Controller
  18. }
  19. // Connect ws链接
  20. // @Description 风险测评同步接口
  21. // @Success 200 {object} controllers.BaseResponse
  22. // @router /connect [get]
  23. func (c *WebSocketController) Connect() {
  24. ws, err := upgrader.Upgrade(c.Ctx.ResponseWriter, c.Ctx.Request, nil)
  25. test := c.Ctx.Request.Header.Get("Authorization")
  26. fmt.Println("发大水范德萨" + test)
  27. if err != nil {
  28. //beego.Error(err)
  29. return
  30. }
  31. defer ws.Close()
  32. for {
  33. var msg []byte
  34. _, msg, err = ws.ReadMessage()
  35. if err != nil {
  36. logger.Error("", err)
  37. break
  38. }
  39. // 处理接收到的消息
  40. fmt.Printf("Received: %s\n", msg)
  41. // 发送消息回客户端
  42. err = ws.WriteMessage(websocket.TextMessage, []byte("Server: "+string(msg)))
  43. if err != nil {
  44. //beego.Error(err)
  45. break
  46. }
  47. time.Sleep(time.Second) // 模拟延迟
  48. }
  49. }