safe

package
v0.12.2 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2022 License: MIT Imports: 2 Imported by: 11

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Close

func Close(closer io.Closer, handler func(error))

Close gracefully closes the io.Closer and calls the handler if an error occurred.

func Handler(rw http.ResponseWriter, req *http.Request) {

	defer safe.Close(req.Body, func(err error) { log.Println(err) })

	var data map[string]interface{}
	if err := json.NewDecoder(req.Body).Decode(&data); err != nil {
		rw.WriteHeader(http.StatusBadRequest)
		return
	}
	...
}

func Do added in v0.0.6

func Do(action func() error, handler func(error))

Do reliably runs the action and captures panic as its error. If an error is not nil, it passes it to the handler.

go safe.Do(
	func() error { ... },
	func(err error) {
		if recovered, is := errors.Unwrap(err).(errors.Recovered); is {
			log.Println(recovered.Cause())
		}
		log.Println(err)
	},
)

Types

type Closer

type Closer func() error

The Closer type is an adapter to allow the use of ordinary functions as the io.Closer interface. If fn is a function with the appropriate signature, Closer(fn) is a Closer that calls fn. It can be used by the Close function.

ticket, err := semaphore.Acquire(breaker.BreakByTimeout(time.Second))
if err != nil {
	log.Fatal(err)
}
defer safe.Close(safe.Closer(ticket), func(err error) { log.Println(err) })

func (Closer) Close

func (fn Closer) Close() error

Close releases resources associated with the Closer.

Jump to

Keyboard shortcuts

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