Skip to content
/ signal Public

This repository provides helpers with `os.Signal` std library

License

Notifications You must be signed in to change notification settings

gol4ng/signal

Repository files navigation

gol4ng/signal: simple POSIX signal subscriber

Build Status Maintainability Test Coverage Go Report Card

signal

This repository provides helpers with POSIX signal(7)

Installation

go get -u github.com/gol4ng/signal

Quick Start

Subscriber

Signal subscriber that allows you to attach a callback to an os.Signal notification.

Useful to react to any os.Signal.

It returns an unsubscribe function that can gracefully stop some http server and clean allocated object

⚠️ If you defer unsubcribe dont forget the final (), If you forget it go defer will execute the subscribe process

defer signal.Subscribe(func(){}, signals...)()

package main

import (
	"fmt"
	"os"
	"syscall"
	"time"

	"github.com/gol4ng/signal"
)

func main() {
	defer signal.Subscribe(func(signal os.Signal) {
		fmt.Println("this code is execute when signal os.Interrupt, syscall.SIGTERM was received")
	}, os.Interrupt, syscall.SIGTERM)()

    // your application code here
}

With killer

The killer subscriber will register your signal handler, but it register another one that gonna to kill (os.Exit) application if 2 killer signals was received.

package main

import (
	"fmt"
	"os"
	"time"
	"syscall"

	"github.com/gol4ng/signal"
)

func main() {
    defer signal.SubscribeWithKiller(func(signal os.Signal) {
      // here you can implement your application stopping steps
		fmt.Println("this code is execute when signal os.Interrupt, syscall.SIGTERM was received")
    }, os.Interrupt, syscall.SIGTERM)()

    // your application code here
}