Skip to content

Instantly share code, notes, and snippets.

@navono
Created June 18, 2019 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save navono/bda00c595bd685b59f1cc2e610d39c09 to your computer and use it in GitHub Desktop.
Save navono/bda00c595bd685b59f1cc2e610d39c09 to your computer and use it in GitHub Desktop.
Golang graceful stop
package main
import (
"os"
"os/signal"
"syscall"
"fmt"
"time"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w,"Server is running")
})
var gracefulStop = make(chan os.Signal)
signal.Notify(gracefulStop, syscall.SIGTERM)
signal.Notify(gracefulStop, syscall.SIGINT)
go func() {
sig := <-gracefulStop
fmt.Printf("caught sig: %+v", sig)
fmt.Println("Wait for 2 second to finish processing")
time.Sleep(2*time.Second)
os.Exit(0)
}()
http.ListenAndServe(":8080",nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment