Documentation ¶
Overview ¶
Package shutdown provides simple shutdown signals handler with callback
package main import ( "context" "net/http" "os" "time" "log" "github.com/vardius/shutdown" ) func main() { ctx := context.Background() http.HandleFunc("/", func(w http.ResponseWriter, _ *http.Request) { io.WriteString(w, "Hello!\n") }) stop := func() { ctx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() log.Printf("shutting down...\n") if err := srv.Shutdown(ctx); err != nil { log.Printf("shutdown error: %v\n", err) } else { log.Printf("gracefully stopped\n") } } go func() { log.Printf("%v\n", http.ListenAndServe(":8080", nil)) stop() os.Exit(1) }() }
Package shutdown provides simple shutdown signals handler with callback handler
Example ¶
package main import ( "fmt" "syscall" "time" "github.com/vardius/shutdown" ) func main() { // mock shutdown signal Ctrl + C go func() { time.Sleep(10 * time.Millisecond) syscall.Kill(syscall.Getpid(), syscall.SIGINT) }() shutdown.GracefulStop(func() { fmt.Println("shutdown") }) }
Output: shutdown
Example (Second) ¶
package main import ( "fmt" "syscall" "time" "github.com/vardius/shutdown" ) func main() { // mock shutdown signal Ctrl + C followed by second Ctrl + C go func() { // first signal interrupt time.Sleep(10 * time.Millisecond) syscall.Kill(syscall.Getpid(), syscall.SIGINT) // second signal kill time.Sleep(10 * time.Millisecond) syscall.Kill(syscall.Getpid(), syscall.SIGINT) }() shutdown.GracefulStop(func() { time.Sleep(100 * time.Millisecond) fmt.Println("shutdown") }) }
Output:
Example (Third) ¶
package main import ( "context" "fmt" "log" "net/http" "syscall" "time" "github.com/vardius/shutdown" ) func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) { fmt.Fprintf(w, "Hello!") }) httpServer := &http.Server{ Addr: ":8080", Handler: mux, } stop := func() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := httpServer.Shutdown(ctx); err != nil { log.Printf("shutdown error: %v\n", err) } else { log.Printf("gracefully stopped\n") } } // mock shutdown signal Ctrl + C go func() { // first signal interrupt time.Sleep(10 * time.Millisecond) syscall.Kill(syscall.Getpid(), syscall.SIGINT) }() shutdown.GracefulStop(stop) }
Output: gracefully stopped
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GracefulStop ¶
func GracefulStop(stop func())
GracefulStop handles signal and graceful shutdown by executing callback function when signal is received callback is called followed after by os.Exit(0), it is responsibility of callback to handle timeout if second signal is received will terminate process by a call to os.Exit(1)
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.