From a34f83e68466507d8a8f59db74483f916d16ebed Mon Sep 17 00:00:00 2001 From: Matthew Rich Date: Thu, 3 Oct 2024 23:31:53 +0000 Subject: [PATCH] add close injector to allow auto-closing the wrapped writers --- internal/ext/addcloser.go | 31 +++++++++++++++++++++++++++++++ internal/ext/addcloser_test.go | 19 +++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 internal/ext/addcloser.go create mode 100644 internal/ext/addcloser_test.go 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()) +}