Clavin June
Posted on • Originally published atclavinjune.dev on
Golang HTTP Server Graceful Shutdown
packagemainimport("context""errors""log""net/http""os""os/signal""syscall""time")funccreateChannel()(chanos.Signal,func()){stopCh:=make(chanos.Signal,1)signal.Notify(stopCh,os.Interrupt,syscall.SIGTERM,syscall.SIGINT)returnstopCh,func(){close(stopCh)}}funcstart(server*http.Server){log.Println("application started")iferr:=server.ListenAndServe();err!=nil&&!errors.Is(err,http.ErrServerClosed){panic(err)}else{log.Println("application stopped gracefully")}}funcshutdown(ctxcontext.Context,server*http.Server){ctx,cancel:=context.WithTimeout(ctx,5*time.Second)defercancel()iferr:=server.Shutdown(ctx);err!=nil{panic(err)}else{log.Println("application shutdowned")}}funcmain(){log.SetFlags(log.Lshortfile)s:=&http.Server{}gostart(s)stopCh,closeCh:=createChannel()defercloseCh()log.Println("notified:",<-stopCh)shutdown(context.Background(),s)}
runtime:
$go run main.gomain.go:24: application started^Cmain.go:50: notified: interrupt# ctrl+cmain.go:28: application stopped gracefullymain.go:39: application shutdowned$
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse