cleanup

package
v1.47.1 Latest Latest
Warning

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

Go to latest
Published: Aug 4, 2022 License: Apache-2.0, Apache-2.0 Imports: 0 Imported by: 0

Documentation

Overview

Package cleanup provides helpers to make it easy to do cleanups.

For example, if a function involves a few separate sub-calls with their own cleanups, a typical code would have to do something like the following:

resource1, cleanup1, err := doFirst()
if err != nil { .... }

resource2, cleanup2, err := doSecond()
if err != nil {
    defer cleanup1()
    nil, nil, return err
}

resource3, cleanup3, err := doThird()
if err != nil {
    defer cleanup1()
    defer cleanup2()
    nil, nil, return err
}
cleanupAll = func() {
   defer cleanup1()
   defer cleanup2()
   cleanup3()
}
return combine(resource1, resource2, resource3), cleanupAll, nil

The code above is both error prone and unsightly. With this package it would look like so:

var cleanup1, cleanup2, cleanup2 func()
cleanups := cleanups.Funcs{&cleanup1, &cleanup2, &cleanup3}
defer cleanups.Run()

resource1, cleanup1, err := doFirst()
if err != nil { return err }

resource2, cleanup2, err := doSecond()
if err != nil { return err }

resource3, cleanup3, err := doThird()
if err != nil { return err }

return combine(resource1, resource2, resource3), cleanups.All(), nil

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Funcs

type Funcs []*func()

Funcs is an array of function pointers. The actual pointers should not be nil though what they point to can be nil.

Example
package main

import (
	"fmt"

	"github.com/getoutreach/gobox/pkg/cleanup"
)

func main() {
	var cleanup1, cleanup2, cleanup3 func()
	cleanups := cleanup.Funcs{&cleanup1, &cleanup2, &cleanup3}
	defer cleanups.Run()

	cleanup1 = func() { fmt.Println("first") }
	cleanup2 = func() { fmt.Println("second") }
	cleanup3 = func() { fmt.Println("third") }

	// you can return this.  once All is called, cleanups.Run does
	// nothing.
	all := cleanups.All()

	// calling all causes all the cleanup functions to be called.
	all()

}
Output:

third
second
first

func (*Funcs) All

func (f *Funcs) All() func()

All zeros the functions list. It captures the list before zeroing and returns Run. Executing the returned function will effectively call all the entries that used to exist in f in reverse order.

func (*Funcs) Run

func (f *Funcs) Run()

Run executes all the functions in reverse order ensuring that even if one panics, the following functions are still called.

Jump to

Keyboard shortcuts

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