From aef4dd3fe78bea7babc7b9b4dd2a1545ee504542 Mon Sep 17 00:00:00 2001 From: Dreamacro <8615343+Dreamacro@users.noreply.github.com> Date: Mon, 25 Apr 2022 23:22:58 +0800 Subject: [PATCH] Fix: make log api unblocked --- hub/route/server.go | 20 ++++++++++++++++---- log/log.go | 6 +++--- 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/hub/route/server.go b/hub/route/server.go index a6632071..d5d8f726 100644 --- a/hub/route/server.go +++ b/hub/route/server.go @@ -208,16 +208,27 @@ func getLogs(w http.ResponseWriter, r *http.Request) { render.Status(r, http.StatusOK) } + ch := make(chan log.Event, 1024) sub := log.Subscribe() defer log.UnSubscribe(sub) buf := &bytes.Buffer{} - var err error - for elm := range sub { - buf.Reset() - log := elm.(*log.Event) + + go func() { + for elm := range sub { + log := elm.(log.Event) + select { + case ch <- log: + default: + } + } + close(ch) + }() + + for log := range ch { if log.LogLevel < level { continue } + buf.Reset() if err := json.NewEncoder(buf).Encode(Log{ Type: log.Type(), @@ -226,6 +237,7 @@ func getLogs(w http.ResponseWriter, r *http.Request) { break } + var err error if wsConn == nil { _, err = w.Write(buf.Bytes()) w.(http.Flusher).Flush() diff --git a/log/log.go b/log/log.go index 3a7ea729..ba706e5f 100644 --- a/log/log.go +++ b/log/log.go @@ -74,7 +74,7 @@ func SetLevel(newLevel LogLevel) { level = newLevel } -func print(data *Event) { +func print(data Event) { if data.LogLevel < level { return } @@ -91,8 +91,8 @@ func print(data *Event) { } } -func newLog(logLevel LogLevel, format string, v ...any) *Event { - return &Event{ +func newLog(logLevel LogLevel, format string, v ...any) Event { + return Event{ LogLevel: logLevel, Payload: fmt.Sprintf(format, v...), }