add close injector to allow auto-closing the wrapped writers
This commit is contained in:
parent
eaaf0f8931
commit
a34f83e684
31
internal/ext/addcloser.go
Normal file
31
internal/ext/addcloser.go
Normal file
@ -0,0 +1,31 @@
|
||||
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. 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()
|
||||
}
|
19
internal/ext/addcloser_test.go
Normal file
19
internal/ext/addcloser_test.go
Normal file
@ -0,0 +1,19 @@
|
||||
// Copyright 2024 Matthew Rich <matthewrich.conf@gmail.com>. 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())
|
||||
}
|
Loading…
Reference in New Issue
Block a user