-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.go
85 lines (73 loc) · 2.03 KB
/
app.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package main
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
)
// app encapsulates information needed for our
// application to run.
type app struct {
port int
watchdog *watchdog
}
// newApp creates a new application struct.
func newApp(port int, requests []*dnsStream) *app {
w := newWatchdog(requests)
return &app{
port: port,
watchdog: w,
}
}
// beforeListen implements the logic to be able to start
// any kind of process before we start our web browser. Currently
// we start the watchdog process in a new goroutine to avoid blocking
// the starting of the webserver.
func (a *app) beforeListen() {
go a.watchdog.watch()
}
// run is responsible for running our webserver and also shut it down along
// with the watchdog processes.
func (a *app) run() error {
// Initialize HTTP server
hostPort := fmt.Sprintf(":%d", a.port)
server := &http.Server{
Addr: hostPort,
ReadHeaderTimeout: 5 * time.Second,
}
http.Handle("/metrics", promhttp.Handler())
http.HandleFunc("/live", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
http.HandleFunc("/ready", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
})
// Start listening asynchronously
go func() {
log.Info("Starting server on port:", a.port)
if err := server.ListenAndServe(); err != nil {
log.Error("Failed to start listening server")
panic(err)
}
}()
// Setting up signal capturing
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, syscall.SIGINT, syscall.SIGTERM)
// Waiting for SIGINT/SIGTERM
<-shutdown
// Kill watchdog internal loop
a.watchdog.stop()
// Shut down server, waiting 5secs for all requests before kill them.
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
log.Info("Shutting down...")
if err := server.Shutdown(ctx); err != nil {
log.Error("Failed to stop listening server")
}
return nil
}