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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With