accesscontrol.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package handler
  2. import (
  3. "city_chips/internal/service"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "github.com/spf13/viper"
  8. "time"
  9. )
  10. type AccessControlHandler struct {
  11. *Handler
  12. accessControlService service.AccessControlService
  13. conf *viper.Viper
  14. }
  15. func NewAccessControlHandler(handler *Handler, accessControlService service.AccessControlService, conf *viper.Viper) *AccessControlHandler {
  16. return &AccessControlHandler{
  17. Handler: handler,
  18. accessControlService: accessControlService,
  19. conf: conf,
  20. }
  21. }
  22. // GetAccessControl SSE实时推送消息
  23. func (h *AccessControlHandler) GetAccessControl(c *gin.Context) {
  24. // 设置响应头
  25. c.Header("Content-Type", "text/event-stream")
  26. c.Header("Cache-Control", "no-cache")
  27. c.Header("Connection", "keep-alive")
  28. // 监听客户端断开连接
  29. conn := true
  30. notify := c.Writer.CloseNotify()
  31. type Response struct {
  32. RequestId string `protobuf:"bytes,1,opt,name=requestId,proto3" json:"requestId,omitempty"`
  33. Code int32 `protobuf:"varint,2,opt,name=code,proto3" json:"code,omitempty"`
  34. Msg string `protobuf:"bytes,3,opt,name=msg,proto3" json:"msg,omitempty"`
  35. Data any `json:"data"`
  36. }
  37. var response Response
  38. count := 0
  39. for conn {
  40. select {
  41. case <-notify:
  42. conn = false
  43. fmt.Println("断开连接")
  44. return
  45. default:
  46. count = count + 1
  47. sprintf := fmt.Sprintf("循环次数%v", count)
  48. response.Code = 200
  49. response.Msg = "查询成功"
  50. response.Data = sprintf
  51. res, _ := json.Marshal(&response)
  52. fmt.Fprintf(c.Writer, "data: %s\n\n", string(res))
  53. c.Writer.Flush()
  54. time.Sleep(5 * time.Second)
  55. }
  56. getString := h.conf.GetString("lifang.baseUrl.Login")
  57. h.logger.Info("测试配置文件")
  58. fmt.Println(getString)
  59. }
  60. }