lundi 15 mars 2021

How to handle OS signals in golang when using Cobra

I have a program which uses cobra to parse command line arguments. Depending on the arguments different parts of the code will be executed. In essence the program starts an infinite process that processes incoming data, e.g. via network. The main function in my program is:

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

    log "github.com/sirupsen/logrus"

    "github.com/munnik/gosk/cmd"
)

func main() {
    signalChannel := make(chan os.Signal, 1)
    signal.Notify(signalChannel)
    go func() {
        for {
            s := <-signalChannel
            // https://www.computerhope.com/unix/signals.htm
            if s == syscall.SIGQUIT || s == syscall.SIGTERM || s == syscall.SIGINT {
                log.Panic(fmt.Sprintf("Received signal: %s, trying to graceful stop the process", s))
            }
        }
    }()

    cmd.Execute()
}

When the log.panic (I also tried os.exit) function is called the deferred function for closing the network, database etc are not called. Is there a way to achieve this in a nice way without repeating the signal handling in different parts of the code?

Aucun commentaire:

Enregistrer un commentaire