forked from SenseUnit/dumbproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
logwriter.go
57 lines (50 loc) · 929 Bytes
/
logwriter.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
package main
import (
"errors"
"io"
"time"
)
const MAX_LOG_QLEN = 128
const QUEUE_SHUTDOWN_TIMEOUT = 500 * time.Millisecond
type LogWriter struct {
writer io.Writer
ch chan []byte
done chan struct{}
}
func (lw *LogWriter) Write(p []byte) (int, error) {
if p == nil {
return 0, errors.New("Can't write nil byte slice")
}
buf := make([]byte, len(p))
copy(buf, p)
select {
case lw.ch <- buf:
return len(p), nil
default:
return 0, errors.New("Writer queue overflow")
}
}
func NewLogWriter(writer io.Writer) *LogWriter {
lw := &LogWriter{writer,
make(chan []byte, MAX_LOG_QLEN),
make(chan struct{})}
go lw.loop()
return lw
}
func (lw *LogWriter) loop() {
for p := range lw.ch {
if p == nil {
break
}
lw.writer.Write(p)
}
lw.done <- struct{}{}
}
func (lw *LogWriter) Close() {
lw.ch <- nil
timer := time.After(QUEUE_SHUTDOWN_TIMEOUT)
select {
case <-timer:
case <-lw.done:
}
}