This commit is contained in:
Bel LaPointe
2025-04-24 21:50:18 -06:00
parent 36f8efd0e7
commit b7a7f2a82f
9 changed files with 278 additions and 0 deletions

28
src/cleanup/cleanup.go Normal file
View File

@@ -0,0 +1,28 @@
package cleanup
import "context"
const ctxKey = "__cleanup"
func Inject(ctx context.Context, foo func()) context.Context {
before := Extract(ctx)
after := func() {
foo()
before()
}
return context.WithValue(ctx, ctxKey, after)
}
func Extract(ctx context.Context) func() {
v := ctx.Value(ctxKey)
if v == nil {
return func() {}
}
v2, _ := v.(func())
if v2 == nil {
return func() {}
}
return v2
}

View File

@@ -0,0 +1,33 @@
package cleanup_test
import (
"context"
"show-rss/src/cleanup"
"testing"
)
func TestCleanup(t *testing.T) {
ctx := context.Background()
called := make([]bool, 100)
for i := range called {
i := i
ctx = cleanup.Inject(ctx, func() {
t.Logf("cleaning %d", i)
if i < len(called)-1 && !called[i+1] {
t.Errorf("cleaning %d before %d", i, i+1)
}
called[i] = true
})
}
t.Logf("cleaning")
cleanup.Extract(ctx)()
t.Logf("cleaned")
for i := range called {
if !called[i] {
t.Fatalf("missing called[%d]", i)
}
}
}