/
linesplittertee.go
44 lines (35 loc) · 992 Bytes
/
linesplittertee.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Plumbing for teeing/tailing log messages. Plop this between your root logger and stderr
// and you'll be tailing log messages efficiently and programmatically for e.g. your GUI
package logtee
import (
"io"
"strings"
"sync"
)
type lineSplitterTee struct {
buf []byte // buffer before receiving \n
lineCompleted func(string)
mu sync.Mutex
}
// returns io.Writer that tees full lines to lineCompleted callback
func NewLineSplitterTee(sink io.Writer, lineCompleted func(string)) io.Writer {
return io.MultiWriter(sink, &lineSplitterTee{
buf: []byte{},
lineCompleted: lineCompleted,
})
}
func (l *lineSplitterTee) Write(data []byte) (int, error) {
l.mu.Lock()
defer l.mu.Unlock()
l.buf = append(l.buf, data...)
// as long as we have lines, chop the buffer down
for {
idx := strings.IndexByte(string(l.buf), '\n')
if idx == -1 {
break
}
l.lineCompleted(string(l.buf[0:idx]))
l.buf = l.buf[idx+1:]
}
return len(data), nil
}