Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Clavin June
Clavin June

Posted on • Originally published atclavinjune.dev on

     

Golang HTTP Server Graceful Shutdown

Sunday Snippet #6 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)}
Enter fullscreen modeExit fullscreen mode

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$
Enter fullscreen modeExit fullscreen mode

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

a bunch of perceptrons
  • Location
    Jakarta, Indonesia
  • Joined

More fromClavin June

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp