vrecan/death

Feature request: CloserFunc

kaedys opened this issue · 1 comments

So, currently, Death requires the structure you hand it to have a "Close()" method. It would be nice to also be able to register anonymous functions, or even other-named functions with the same traits (no arguments, no return value), for use without having to define a "Close" method for your struct. For that, I propose adding the following definitions:

type closerFunc struct {
    f func()
}

func (c *closerFunc) Close() {
    c.f()
}

func CloserFunc(f func()) io.Closer {
    return &closerFunc{f: f}
}

Now you can make a call like the following:

death.NewDeath(syscall.SIGINT, syscall.SIGTERM).WaitForDeath(CloserFunc(func() {
    // do some stuff
    // call some other function for cleanup
}))

Or:

type Foo struct {
    // stuff
}

func (foo Foo) StopStuff() {
    // do stop things
}

func main() {
    var foo Foo
    death.NewDeath(syscall.SIGINT, syscall.SIGTERM).WaitForDeath(CloserFunc(foo.StopStuff))
}

This lets you hand the WaitForDeath() anonymous functions, non-method functions, and methods with the same signature but a different name, and it'll still see them as io.Closers.

This is the same strategy that the standard library package net/http uses, with its Handler interface (which requires a method with the signature ServeHTTP(ResponseWriter, *Request)). It defines a second type, HandlerFunc, that allows you to use anonymous functions or other-named lambdas as a Handler without having to define a type to hold them.

Thanks for the suggestion. I do like this approach more then requiring a close method.