No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

log_stream_routes.go 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package routes
  2. import (
  3. "fmt"
  4. "net/http"
  5. "time"
  6. "git.x2erp.com/qdy/go-base/webx/router"
  7. "git.x2erp.com/qdy/go-svc-code/internal/opencode"
  8. )
  9. // RegisterLogStreamRoutes 注册日志流路由
  10. func RegisterLogStreamRoutes(ws *router.RouterService, process *opencode.Process) {
  11. // 日志流路由
  12. // 注意:这个路由需要直接处理 HTTP 流,不能使用标准的 router 包装
  13. // 我们将注册一个原始的 HTTP 处理器到 gin 引擎
  14. // 这个函数将由 main.go 中的额外注册调用
  15. }
  16. // LogStreamHandler 日志流的 HTTP 处理器
  17. func LogStreamHandler(process *opencode.Process) http.HandlerFunc {
  18. return func(w http.ResponseWriter, r *http.Request) {
  19. // 设置 SSE 头
  20. w.Header().Set("Content-Type", "text/event-stream")
  21. w.Header().Set("Cache-Control", "no-cache")
  22. w.Header().Set("Connection", "keep-alive")
  23. w.Header().Set("Access-Control-Allow-Origin", "*")
  24. flusher, ok := w.(http.Flusher)
  25. if !ok {
  26. http.Error(w, "Streaming unsupported", http.StatusInternalServerError)
  27. return
  28. }
  29. // 获取日志通道
  30. logChan := process.GetLogs()
  31. if logChan == nil {
  32. http.Error(w, "日志通道不可用", http.StatusInternalServerError)
  33. return
  34. }
  35. // 发送初始消息
  36. fmt.Fprintf(w, "data: 连接到 opencode 日志流\n\n")
  37. flusher.Flush()
  38. // 监听日志通道
  39. for {
  40. select {
  41. case log, ok := <-logChan:
  42. if !ok {
  43. // 通道关闭
  44. fmt.Fprintf(w, "data: 日志流已结束\n\n")
  45. flusher.Flush()
  46. return
  47. }
  48. // 发送日志
  49. fmt.Fprintf(w, "data: %s\n\n", log)
  50. flusher.Flush()
  51. case <-r.Context().Done():
  52. // 客户端断开连接
  53. return
  54. case <-time.After(30 * time.Second):
  55. // 发送心跳保持连接
  56. fmt.Fprintf(w, ": heartbeat\n\n")
  57. flusher.Flush()
  58. }
  59. }
  60. }
  61. }