-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.go
83 lines (69 loc) · 1.74 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
package prbot
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/rs/zerolog/log"
)
type Server struct {
*http.Server
config *Config
}
// NewServer creates and configures a server
func NewServer(cfg *Config, routes http.Handler) *Server {
srv := http.Server{
Addr: fmt.Sprintf(":%d", cfg.Server.Port),
Handler: routes,
ReadTimeout: 5 * time.Second,
WriteTimeout: 5 * time.Second,
IdleTimeout: 10 * time.Second,
}
return &Server{
Server: &srv,
config: cfg,
}
}
func (srv *Server) Start() {
if srv.config.Env == "local" {
srv.startHTTP()
} else {
srv.startHTTPS()
}
}
func (srv *Server) startHTTP() {
log.Info().Msg("Starting HTTP Server....")
err := srv.ListenAndServe()
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Err(err).Msg("error starting server")
os.Exit(1)
}
}
func (srv *Server) startHTTPS() {
log.Info().Msg("Starting HTTPS Server....")
certFile := srv.config.Server.TLS.CertFile
KeyFile := srv.config.Server.TLS.KeyFile
err := srv.ListenAndServeTLS(certFile, KeyFile)
if err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Err(err).Msg("error starting server")
os.Exit(1)
}
}
func (srv *Server) WaitForGracefulShutdown() {
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
sig := <-quit
log.Info().Str("Reason", sig.String()).Msg("Server is shutting down.")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
srv.SetKeepAlivesEnabled(false)
if err := srv.Shutdown(ctx); err != nil {
log.Err(err).Msg("Could not gracefully shutdown the server")
os.Exit(1)
}
log.Info().Msg("Server stopped")
}