forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
59 lines (54 loc) · 1.21 KB
/
writer.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
package prefixwriter
import (
"bytes"
"io"
)
// prefixWriter is a writer that prefixes every line it writes with a prefix
type prefixWriter struct {
// prefix is the prefix for every line
prefix string
// atStart is true if the writer is positioned at the start of a line
atStart bool
// writer is the actual internal writer
writer io.Writer
}
// New creates a writer that prepends a prefix to every line it writes
func New(prefix string, w io.Writer) io.Writer {
return &prefixWriter{
writer: w,
atStart: true,
prefix: prefix,
}
}
func (w *prefixWriter) Write(p []byte) (n int, err error) {
segments := bytes.Split(p, []byte("\n"))
for i, s := range segments {
if len(s) > 0 {
if w.atStart {
// write the prefix if at start of a line
_, err = w.writer.Write([]byte(w.prefix))
if err != nil {
return
}
}
_, err = w.writer.Write(s)
if err != nil {
return
}
w.atStart = false
} else {
// If segment is empty, we're at start of a line
w.atStart = true
}
if i < (len(segments) - 1) {
// If not at the end of the segments, write a newline
_, err = w.writer.Write([]byte("\n"))
if err != nil {
return
}
w.atStart = true
}
}
n = len(p)
return
}