Skip to content

Instantly share code, notes, and snippets.

@billyfbrain
Last active December 18, 2022 07:45
Show Gist options
  • Select an option

  • Save billyfbrain/0326257d4de4fd36579a to your computer and use it in GitHub Desktop.

Select an option

Save billyfbrain/0326257d4de4fd36579a to your computer and use it in GitHub Desktop.
golang graceful shutdown tcp listener
cmdAddr, _ := net.ResolveTCPAddr("tcp", n.cfg.Addr)
lcmd, err := net.ListenTCP("tcp", cmdAddr)
if err != nil {
log.Fatalln(err)
}
defer lcmd.Close()
quitChan := make(chan os.Signal, 1)
signal.Notify(quitChan, os.Interrupt, os.Kill, syscall.SIGTERM)
wg := sync.WaitGroup{}
for {
select {
case <-quitChan:
lcmd.Close()
wg.Wait()
return
default:
}
lcmd.SetDeadline(time.Now().Add(1e9))
conn, err := lcmd.AcceptTCP()
if opErr, ok := err.(*net.OpError); ok && opErr.Timeout() {
continue
}
if err != nil {
log.WithError(err).Errorln("Listener accept")
continue
}
wg.Add(1)
go func(){
wg.Done()
n.handleRequest(conn)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment