shad-go/lectures/06-http/gracefulshutdown/gracefulshutdown.go

47 lines
767 B
Go
Raw Normal View History

2020-04-02 11:42:31 +00:00
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
2020-04-02 14:01:16 +00:00
func handler(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("pong"))
}
2020-04-02 11:42:31 +00:00
2020-04-02 14:01:16 +00:00
func run() error {
2020-04-02 11:42:31 +00:00
srv := &http.Server{
Addr: ":8080",
Handler: http.HandlerFunc(handler),
}
serveChan := make(chan error, 1)
go func() {
serveChan <- srv.ListenAndServe()
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, syscall.SIGINT, syscall.SIGTERM)
select {
case <-stop:
fmt.Println("shutting down gracefully")
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return srv.Shutdown(ctx)
2020-04-02 14:01:16 +00:00
2020-04-02 11:42:31 +00:00
case err := <-serveChan:
return err
}
}