Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Last active April 17, 2022 20:08
Show Gist options
  • Select an option

  • Save miguelmota/978ecabf04e1620798f6ec2c330a28f2 to your computer and use it in GitHub Desktop.

Select an option

Save miguelmota/978ecabf04e1620798f6ec2c330a28f2 to your computer and use it in GitHub Desktop.
Golang graceful quit (exit) example
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)
}
@solidiquis

Copy link
Copy Markdown

Thanks for this!

@aky91

aky91 commented Apr 17, 2022

Copy link
Copy Markdown

This was really helpful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment