summaryrefslogtreecommitdiffstats
path: root/pkg/common/line_writer.go
blob: 203519975328ff739711bc7eb25abcbf670af988 (plain)
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
package common

import (
	"bytes"
	"io"
)

// LineHandler is a callback function for handling a line
type LineHandler func(line string) bool

type lineWriter struct {
	buffer   bytes.Buffer
	handlers []LineHandler
}

// NewLineWriter creates a new instance of a line writer
func NewLineWriter(handlers ...LineHandler) io.Writer {
	w := new(lineWriter)
	w.handlers = handlers
	return w
}

func (lw *lineWriter) Write(p []byte) (n int, err error) {
	pBuf := bytes.NewBuffer(p)
	written := 0
	for {
		line, err := pBuf.ReadString('\n')
		w, _ := lw.buffer.WriteString(line)
		written += w
		if err == nil {
			lw.handleLine(lw.buffer.String())
			lw.buffer.Reset()
		} else if err == io.EOF {
			break
		} else {
			return written, err
		}
	}

	return written, nil
}

func (lw *lineWriter) handleLine(line string) {
	for _, h := range lw.handlers {
		ok := h(line)
		if !ok {
			break
		}
	}
}