signal

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2024 License: MIT Imports: 4 Imported by: 0

README

go-signal

Go Reference Go Report Card

Package signal provides simple, semantic manipulation of the operating system's signal processing.

Installation
go get -u github.com/wjiec/go-signal
Quick Start

Listens to the user's signal to exit the program and performs cleanup

func main() {
	f, _ := os.Open("path/to/your/config")
	s, _ := http.NewServer(f)

	signal.Once(syscall.SIGTERM).Notify(context.TODO(), func(sig os.Signal) {
		_ = s.Shutdown()
		_ = f.Close()
	})

	s.Start()
}

Listening for SIGUSR1 signals from users and performing services reload

func main() {
	ngx, _ := nginx.New(cfg)

	signal.When(syscall.SIGUSR1).Notify(context.TODO(), func(sig os.Signal) {
		_ = ngx.Reload()
	})
}

Create a context object using the specified signals and cancel the current context when the signal arrived

func main() {
    var db *sql.DB

	ctx, cancel := signal.With(context.TODO(), syscall.SIGTERM)
	defer cancel()

	_, _ = db.QueryContext(ctx, "select id,username,password from `user`")
}
License

Released under the MIT License.

Documentation

Overview

Package signal provides simple, semantic manipulation of the operating system's signal processing.

Index

Constants

View Source
const (
	// SigCtx represents signal from cancelled context
	SigCtx = syscall.Signal(0xff)
)

Variables

This section is empty.

Functions

func With

func With(parent context.Context, signals ...os.Signal) (context.Context, context.CancelFunc)

With returns a copy of the parent context that is marked done when one of the listed signals arrives, when the returned cancel function is called, or when the parent context's canceled, whichever happens first.

Types

type Notifier

type Notifier interface {
	Notify(context.Context, func(sig os.Signal))
}

Notifier creates and listens to a specified system signal and calls a handler when the signal is received or when the context is cancelled.

Notifier will be closed when the context is cancelled and the handler can get an instance of SigCtx (number = 0xff).

methods of the Notifier can be safely called multiple times.

func Once

func Once(signals ...os.Signal) Notifier

Once perform the handler once only when the context is cancelled or when one of the listed signals arrives, after which the Notifier will be closed directly.

func When

func When(signals ...os.Signal) Notifier

When perform the handler function when one of the listed signals arrives.

Notifier created by When can only be closed by canceling the context object.

Jump to

Keyboard shortcuts

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