Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exiting go applications gracefully

Tags:

go

I'm new to Go and I have a few small services running.

When I'm deploying a new version, I typically just upload the new binary, kill the existing process and start a new one.

I'm wondering if this is the correct thing to do, or if there is a better way to do this.

like image 520
Evert Avatar asked Jun 13 '16 20:06

Evert


People also ask

How do I get out of Goroutine gracefully?

Typically, you pass the goroutine a (possibly separate) signal channel. That signal channel is used to push a value into when you want the goroutine to stop. The goroutine polls that channel regularly. As soon as it detects a signal, it quits.


1 Answers

There's nothing wrong in killing the process, replacing and restarting. If you want to do some cleanup on exiting you may do following:

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

func main(){
   //work here

   go gracefulShutdown()
   forever := make(chan int)
   <-forever
}

func gracefulShutdown() {
    s := make(chan os.Signal, 1)
    signal.Notify(s, os.Interrupt)
    signal.Notify(s, syscall.SIGTERM)
    go func() {
        <-s
        fmt.Println("Sutting down gracefully.")
        // clean up here
        os.Exit(0)
    }()
}

If you do kill {pid} (without -9 switch), process will call gracefullShutdown function before terminating.

like image 88
codefreak Avatar answered Oct 13 '22 20:10

codefreak