diff --git a/internal/ext/addcloser.go b/internal/ext/addcloser.go new file mode 100644 index 0000000..75a1e32 --- /dev/null +++ b/internal/ext/addcloser.go @@ -0,0 +1,31 @@ +// Copyright 2024 Matthew Rich . All rights reserved. + +package ext + +import ( + "io" +) + +type Closer func() error + +func WriteAddCloser(w io.WriteCloser, c Closer) io.WriteCloser { + a := writeAddCloser{ WriteCloser: w, AddClose: func() (err error) { + if err = w.Close(); err != nil { + return + } + if c != nil { + return c() + } + return + } } + return a +} + +type writeAddCloser struct { + io.WriteCloser + AddClose Closer +} + +func (w writeAddCloser) Close() error { + return w.AddClose() +} diff --git a/internal/ext/addcloser_test.go b/internal/ext/addcloser_test.go new file mode 100644 index 0000000..cc53937 --- /dev/null +++ b/internal/ext/addcloser_test.go @@ -0,0 +1,19 @@ +// Copyright 2024 Matthew Rich . All rights reserved. + +package ext + +import ( + "testing" + "github.com/stretchr/testify/assert" + "strings" +_ "fmt" +_ "log" +) + +func TestNewWriteAddCloser(t *testing.T) { + var testWriter strings.Builder + + closer := WriteAddCloser(WriteNopCloser(&testWriter), func() error { testWriter.Write([]byte("foo")); return nil }) + closer.Close() + assert.Equal(t, "foo", testWriter.String()) +}