finally

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Dec 23, 2019 License: MIT Imports: 8 Imported by: 0

README

* finally

[[https://godoc.org/github.com/chrisww/finally][https://img.shields.io/badge/godoc-finally-blue.svg]]

Makes sure cleanup functions are called in addition to =defer=.

** Example

#+BEGIN_SRC go
func main() {
	finally.RegisterShutdownHook()

	cleanup := finally.Wrap(func() {
		fmt.Println("Cleaning up")
	})

	defer cleanup()

	// do something
}
#+END_SRC

If the program executes normally, the wrapped function that prints
=Cleaning up= will be called in defer as usual.

However, if the program is terminated by signals like SIGTERM,
deferred functions will not run. And in this case, the wrapped
function will be called in the signal handler registered in
=RegisterShutdownHook=.

The wrapped function is guaranteed to be called only once, either in
=defer= or in signal handlers.

Documentation

Overview

finally is a package helping to enhance cleanup handlers which is usually used with defer. By wrapping functions with finally.Wrap, cleanup handlers are guaranteed to be executed even when the program is terminated by SIGTERM.

Example
package main

import (
	"fmt"

	"github.com/chrisww/finally"
)

func main() {
	finally.RegisterShutdownHook()

	cleanup := finally.Wrap(func() {
		fmt.Println("Cleaning up")
	})

	defer cleanup()

	fmt.Println("Doing something")
}
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func RegisterShutdownHook

func RegisterShutdownHook(signals ...os.Signal)

RegisterShutdownHook registers signal handlers for signals specified in the arguments. If no arguments are specified, os.Interrupt and syscall.SIGTERM are used.

func SetRecordStackTrace

func SetRecordStackTrace(v bool)

SetRecordStackTrace set the config about whether the stacktrace should be saved. If it is set to true, when a panic happenes in a finally handler, the stacktrace will be shown.

func Wrap

func Wrap(handler FinallyHandler) func()

Wrap wraps a function of type FinallyHandler and returns a function to invoke the input function, which can be used in defer. The input function will be called when the program receives shutdown signals or with the returned function. The input function is guranteed to be invoked only once.

func WrapSig

func WrapSig(handler FinallyHandlerSig) func()

WrapSig does exactly the same thing as Wrap, except that the function can accept an argument representing the signal that the program received. If the wrapping function is called, the signal will be nil.

Types

type FinallyHandler

type FinallyHandler func()

type FinallyHandlerSig

type FinallyHandlerSig func(sig os.Signal)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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