multicloser

package
v1.0.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2024 License: Apache-2.0 Imports: 1 Imported by: 4

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

func Append[T Func](c *Closer, fns ...T) *Closer

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.

func (*Closer) Close

func (c *Closer) Close() (err error)

Close runs all closer functions. All closers are guaranteed to run, even if they panic. After all closers run, panics will propagate up the stack.

[Close] also panics if it is called on an already-closed Closer.

type Func

type Func interface {
	func() error | func()
}

Func is the type signature for a closing function. It accepts a function that returns an error or a void function.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL