diff --git a/README.md b/README.md index cf951d9..d3a222f 100644 --- a/README.md +++ b/README.md @@ -35,40 +35,39 @@ For **GoDoc** reference, **visit [pkg.go.dev](https://pkg.go.dev/github.com/vard package main import ( - "context" - "net/http" - "os" - "time" - "log" + "context" + "fmt" + "log" + "net/http" + "syscall" + "time" "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) - }() + 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") + } + } + + shutdown.GracefulStop(stop) // will block until shutdown signal is received } ``` diff --git a/example_test.go b/example_test.go index 80be5fb..3f6d7ef 100644 --- a/example_test.go +++ b/example_test.go @@ -1,7 +1,10 @@ package shutdown_test import ( + "context" "fmt" + "log" + "net/http" "syscall" "time" @@ -9,7 +12,7 @@ import ( ) func Example() { - // mock shutdown signall Ctrl + C + // mock shutdown signal Ctrl + C go func() { time.Sleep(10 * time.Millisecond) syscall.Kill(syscall.Getpid(), syscall.SIGINT) @@ -24,7 +27,7 @@ func Example() { } func Example_second() { - // mock shutdown signall Ctrl + C followed by second Ctrl + C + // mock shutdown signal Ctrl + C followed by second Ctrl + C go func() { // first signal interrupt time.Sleep(10 * time.Millisecond) @@ -42,3 +45,38 @@ func Example_second() { // Output: } + +func Example_third() { + 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 +}