/
server.go
93 lines (76 loc) · 2.01 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
package api
import (
"context"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/seibert-media/golibs/log"
"go.uber.org/zap"
"github.com/canonical-debate-lab/argument-analysis-research/pkg/api/middlewares"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
)
// Server is our default wrapper for routing and serving
type Server struct {
*http.Server
Addr string
Router chi.Router
}
// New Server with default router and middlewares
func New(addr string, dbg bool) *Server {
s := &Server{
Addr: addr,
Router: chi.NewRouter(),
}
s.Router.Use(middleware.RequestID)
s.Router.Use(middleware.RealIP)
s.Router.Use(middleware.Recoverer)
s.Router.Use(middlewares.Logger)
if dbg {
s.Router.Use(middlewares.DevMode)
}
s.Router.Get("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(fmt.Sprintf(`{"status": "ok"}`)))
})
return s
}
// Start the server
func (s *Server) Start(ctx context.Context) error {
ctx = log.WithFields(ctx, zap.String("addr", s.Addr))
s.Server = &http.Server{Addr: s.Addr, Handler: chi.ServerBaseContext(ctx, s.Router)}
log.From(ctx).Info("serving")
err := s.ListenAndServe()
if err != http.ErrServerClosed {
log.From(ctx).Error("serving", zap.Error(err))
return s.Shutdown(ctx)
}
log.From(ctx).Info("stopping", zap.Error(err))
return nil
}
// Shutdown the Server
func (s *Server) Shutdown(ctx context.Context) error {
if s.Server != nil {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
err := s.Server.Shutdown(ctx)
if err != nil {
log.From(ctx).Error("stopping gracefully", zap.Error(err))
return err
}
s.Server = nil
}
return nil
}
// GracefulHandler watches for termination signals and takes care of graceful server shutdown
func (s *Server) GracefulHandler(ctx context.Context) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
<-c
err := s.Shutdown(ctx)
if err != nil {
log.From(ctx).Fatal("handling signal", zap.Error(err))
}
}