cancelable

package
v2.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 29, 2023 License: Apache-2.0 Imports: 1 Imported by: 0

Documentation

Overview

Package cancelable provides a cancelable version of io.Closer.

This is intended to be used by functions where the responsibility for closing a resource sometimes belongs to the function itself (e.g. early returns due to error handling), and sometimes belongs to the caller.

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 is an io.Closer that can be cancelled.

Example
package main

import (
	"fmt"

	"github.com/samuong/alpaca/cancelable"
)

type printCloser struct {
	msg string
}

// Close prints the printCloser's msg on stdout.
func (pc *printCloser) Close() error {
	fmt.Printf("Close() called: %s\n", pc.msg)
	return nil
}

func main() {
	c := create(false) // defer in create() prints once
	c.Close()          // prints again

	c = create(true) // defer cancelled, no print
	c.Close()        // prints

}

func create(doCancel bool) *printCloser {
	pc := &printCloser{fmt.Sprintf("doCancel: %v", doCancel)}

	closer := cancelable.NewCloser(pc)
	defer closer.Close()

	if !doCancel {
		return pc // deferred Close will cause msg to be printed
	}

	closer.Cancel() // Cancel will prevent Close being called from defer
	return pc
}
Output:

Close() called: doCancel: false
Close() called: doCancel: false
Close() called: doCancel: true

func NewCloser

func NewCloser(c io.Closer) *Closer

NewCloser returns a cancelable.Closer that wraps an io.Closer.

func (*Closer) Cancel

func (c *Closer) Cancel()

Cancel turns any future calls to Close into a no-op.

func (*Closer) Close

func (c *Closer) Close() error

Close calls the Close function on the io.Closer (if it has not been cancelled or already closed). It is safe to call this multiple times.

Jump to

Keyboard shortcuts

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