@
nanmu42 #2 想让 main 的 defe 能执行,就需要让 main 正常退出,那在 goroutine 里出错错误的时候,发送 sign 到 main 里等等的 chan 就行了,比如
defer func() {
log.Println("defer")
}()
server := http.Server{
Addr: fmt.Sprintf(":%d", *port),
Handler: downright.SlowHandler(*sleepSeconds),
}
quit := make(chan os.Signal, 1)
go func() {
err := server.ListenAndServe()
if err != http.ErrServerClosed {
log.Printf("ListenAndServe err: %v", err)
quit <- syscall.SIGTERM
}
}()
signal.Notify(quit, os.Interrupt)
<-quit
log.Println("waiting for shutdown finishing...")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("shutdown err: %v", err)
}
log.Println("shutdown finished")
ListenAndServe 不管出现什么级别的错误都可以处理(只要不调用 os.Exit ),毕竟 main 一直在等待新号阻塞着