Skip to content

Commit

Permalink
feat: 尝试改善日志性能
Browse files Browse the repository at this point in the history
  • Loading branch information
devhaozi committed Oct 25, 2024
1 parent 8a1e7ef commit 5ac43df
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion internal/service/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"context"
"github.com/TheTNB/panel/internal/http/request"
"net/http"
"strings"
"sync"
"time"

"github.com/TheTNB/panel/internal/app"
"github.com/TheTNB/panel/internal/biz"
Expand Down Expand Up @@ -100,10 +102,28 @@ func (s *WsService) Exec(w http.ResponseWriter, r *http.Request) {

go func() {
scanner := bufio.NewScanner(out)
var batch []string
ticker := time.NewTicker(200 * time.Millisecond)
defer ticker.Stop()

go func() {
for range ticker.C {
if len(batch) > 0 {
_ = ws.WriteMessage(websocket.TextMessage, []byte(strings.Join(batch, "\n")))
batch = nil
}
}
}()

for scanner.Scan() {
line := scanner.Text()
_ = ws.WriteMessage(websocket.TextMessage, []byte(line))
batch = append(batch, line)
}

if len(batch) > 0 {
_ = ws.WriteMessage(websocket.TextMessage, []byte(strings.Join(batch, "\n")))
}

if err = scanner.Err(); err != nil {
_ = ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "failed to read command output"))
}
Expand Down

0 comments on commit 5ac43df

Please sign in to comment.