-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
58 lines (46 loc) · 1.23 KB
/
main.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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"context"
"net/http"
"os"
"os/signal"
"time"
"gqlgen-starwars/server"
"gqlgen-starwars/server/middlewares"
)
func main() {
var (
logger = middlewares.DefaultLogger
srv = server.NewServer(logger)
)
logger.Infof("Listening for requests on %s", srv.Addr)
// Run our server in a goroutine so that it doesn't block.
go func() {
// Begin listening for requests.
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
logger.WithError(err).Error("Failed to listen and serve")
}
}()
if err := gracefulShutdown(srv); err != nil {
logger.WithError(err).Error("Failed to cleanly shutdown server")
}
logger.Info("Shutting down.")
os.Exit(0)
}
func gracefulShutdown(srv *http.Server) error {
var (
c = make(chan os.Signal, 1)
wait = 15 * time.Second
)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
return srv.Shutdown(ctx)
}