-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
99 lines (77 loc) · 2.19 KB
/
server.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package http
import (
"net/http"
"os"
"os/signal"
"syscall"
"github.com/gorilla/mux"
"context"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
type Server interface {
ListenAndServe(shutDownFn func(), healthCheckFn Endpoint) error
Handle(method string, path string, fn Endpoint)
}
type server struct {
r *mux.Router
srv *http.Server
log Logger
}
func NewServer(port string, log Logger) Server {
s := &server{}
r := mux.NewRouter()
srv := &http.Server{}
srv.Handler = r
srv.Addr = ":" + port
s.r = r
s.srv = srv
s.log = log
s.r.NotFoundHandler = http.HandlerFunc(Json(func(w http.ResponseWriter, r *http.Request) Response {
return &Error{
Message: "Route not found: " + r.URL.Path,
Status: 404,
System: "HTTP",
Series: 404,
}
}))
return s
}
func (s *server) Handle(method string, path string, fn Endpoint) {
s.r.HandleFunc(path, Metrics(path, Json(
Logging(s.log, fn),
))).Methods(method)
}
func (s *server) ListenAndServe(shutDownFn func(), healthCheckFn Endpoint) error {
idleConnsClosed := make(chan struct{})
metricsServer := NewMetricsServer(healthCheckFn)
s.r.Handle("/_/metrics", promhttp.Handler())
s.r.HandleFunc("/_/health", Json(healthCheckFn)).Methods("GET")
go func() {
sigint := make(chan os.Signal, 1)
// interrupt signal sent from terminal
signal.Notify(sigint, os.Interrupt)
// sigterm signal sent from kubernetes
signal.Notify(sigint, syscall.SIGTERM)
<-sigint
s.log.Debug("Shutting down the server")
// We received an interrupt signal, shut down.
if err := s.srv.Shutdown(context.Background()); err != nil {
// Error from closing listeners, or context timeout:
s.log.Warn("HTTP server Shutdown: ", err.Error())
}
s.log.Debug("Shutting down the metrics server")
if err := metricsServer.Shutdown(context.Background()); err != nil {
// Error from closing listeners, or context timeout:
s.log.Warn("Metrics HTTP server Shutdown: ", err.Error())
}
shutDownFn()
close(idleConnsClosed)
}()
if err := s.srv.ListenAndServe(); err != http.ErrServerClosed {
// Error starting or closing listener:
s.log.Warn("HTTP server ListenAndServe: ", err.Error())
return err
}
<-idleConnsClosed
return nil
}