Documentation ¶
Overview ¶
Package multicloser provides a convenient way to join multiple "close" functions together so they can be called together. This is especially useful to group multiple cleanup function calls and return it as a single "closer" to be called later.
Example ¶
package main import ( "fmt" "log" "github.com/abcxyz/pkg/multicloser" ) func setup() (*multicloser.Closer, error) { var closer *multicloser.Closer client1, err := newClient() if err != nil { return closer, fmt.Errorf("failed to create client1: %w", err) } closer = multicloser.Append(closer, client1.Close) client2, err := newClient() if err != nil { return closer, fmt.Errorf("failed to create client2: %w", err) } closer = multicloser.Append(closer, client2.Close) return closer, nil } // client is just a stub to demonstrate something that needs to be closed. type client struct{} func (c *client) Close() error { return nil } func newClient() (*client, error) { return &client{}, nil } func main() { closer, err := setup() defer func() { if err := closer.Close(); err != nil { log.Printf("failed to close: %s\n", err) } }() if err != nil { // handle err } }
Output:
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Closer ¶
type Closer struct {
// contains filtered or unexported fields
}
Closer maintains the ordered list of closing functions. Functions will be run in the order in which they were inserted.
It is not safe to use concurrently without locking.
func Append ¶
Append adds the given closer functions. It handles void and error signatures. Other signatures should use an anonymous function to match an expected signature. This function will always return an instantiated Closer, even if the first argument is nil. Although not recommend, the following is valid for constructing an empty Closer:
closer := append(nil, nil)
The much like the built-in [append] function, the returned Closer is not guaranteed to refer to the same memory as the provided Closer argument.