-
Notifications
You must be signed in to change notification settings - Fork 66
/
doggy_1.8.go
41 lines (31 loc) · 812 Bytes
/
doggy_1.8.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// +build go1.8
package doggy
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"github.com/hnlq715/doggy/utils"
"github.com/spf13/viper"
"go.uber.org/zap"
)
// ListenAndServeGracefully always returns a non-nil error.
func ListenAndServeGracefully(handler http.Handler) error {
l := utils.LogFromContext(context.Background())
h := &http.Server{Addr: viper.GetString("listen"), Handler: handler}
go func() {
if err := h.ListenAndServe(); err != nil {
l.Error("h.ListenAndServe failed", zap.Error(err))
}
}()
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
<-stop
l.Info("Shutting down the server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
h.Shutdown(ctx)
l.Info("Server gracefully stopped")
return nil
}