Is there any API to let the main
goroutine sleep forever?
In other words, I want my project always run except when I stop it.
It depends on use cases to choose what kind of sleep you want.
@icza provides a good and simple solution for literally sleeping forever, but I want to give you some more sweets if you want your system could shutdown gracefully.
You could do something like this:
func mainloop() {
exitSignal := make(chan os.Signal)
signal.Notify(exitSignal, syscall.SIGINT, syscall.SIGTERM)
<-exitSignal
systemTeardown()
}
And in your main:
func main() {
systemStart()
mainloop()
}
In this way, you could not only ask your main to sleep forever, but you could do some graceful shutdown stuff after your code receives INT
or TERM
signal from OS, like ctrl+C
or kill
.