-
Notifications
You must be signed in to change notification settings - Fork 0
/
prefixwriter.go
71 lines (57 loc) · 1.27 KB
/
prefixwriter.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package prefixwriter
import (
"bytes"
"io"
)
// Writer writes specified data, prepending prefix to each new line.
type Writer struct {
backend io.WriteCloser
prefix string
streamStarted bool
lineIncomplete bool
}
// New creates new Writer, that will use `writer` as backend
// and will prepend `prefix` to each line.
func New(writer io.WriteCloser, prefix string) *Writer {
return &Writer{
backend: writer,
prefix: prefix,
}
}
// Writer writes data into Writer.
//
// Signature matches with io.Writer's Write().
func (writer *Writer) Write(data []byte) (int, error) {
var (
reader = bytes.NewBuffer(data)
eofEncountered = false
)
for !eofEncountered {
line, err := reader.ReadString('\n')
if err != nil {
if err != io.EOF {
return 0, err
}
eofEncountered = true
}
if line == "" {
continue
}
if !writer.streamStarted || !writer.lineIncomplete {
line = writer.prefix + line
writer.streamStarted = true
}
writer.lineIncomplete = eofEncountered
_, err = writer.backend.Write([]byte(line))
if err != nil {
return 0, err
}
}
return len(data), nil
}
// Close closes underlying backend writer.
//
// Signature matches with io.WriteCloser's Close().
func (writer *Writer) Close() error {
return writer.backend.Close()
}