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
Click to show internal directories.
Click to hide internal directories.