-
Notifications
You must be signed in to change notification settings - Fork 1
/
sync_writer.go
61 lines (51 loc) · 1.05 KB
/
sync_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
60
61
package clog
import (
"io"
"sync"
)
// syncWriter is a thread safe io.Writer
type syncWriter struct {
io.Writer
sync.Mutex
}
// Write data (thread safe)
func (w *syncWriter) Write(p []byte) (n int, err error) {
w.Lock()
defer w.Unlock()
return w.Writer.Write(p)
}
// fdWriter is an io.Writer that also has an Fd method. The most common
// example of an fdWriter is an *os.File.
type fdWriter interface {
io.Writer
Fd() uintptr
}
// syncFdWriter is a thread safe io.Writer with Fd()
// Inspired by https://github.com/go-kit/log/
type syncFdWriter struct {
fdWriter
sync.Mutex
}
// Write data (thread safe)
func (w *syncFdWriter) Write(p []byte) (n int, err error) {
w.Lock()
defer w.Unlock()
return w.fdWriter.Write(p)
}
// NewSyncWriter creates a thread-safe io.Writer
func NewSyncWriter(writer io.Writer) io.Writer {
fdWriter, ok := writer.(fdWriter)
if ok {
return &syncFdWriter{
fdWriter: fdWriter,
}
}
return &syncWriter{
Writer: writer,
}
}
// Verify interface
var (
_ io.Writer = &syncWriter{}
_ io.Writer = &syncFdWriter{}
)