summaryrefslogtreecommitdiffstats
path: root/pkg/utils/once_writer.go
blob: aecf20369c73b0b49829c9e07c6ba96b76fa7b51 (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
package utils

import (
	"io"
	"sync"
)

// This wraps a writer and ensures that before we actually write anything we call a given function first

type OnceWriter struct {
	writer io.Writer
	once   sync.Once
	f      func()
}

var _ io.Writer = &OnceWriter{}

func NewOnceWriter(writer io.Writer, f func()) *OnceWriter {
	return &OnceWriter{
		writer: writer,
		f:      f,
	}
}

func (self *OnceWriter) Write(p []byte) (n int, err error) {
	self.once.Do(func() {
		self.f()
	})

	return self.writer.Write(p)
}