-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
87 lines (71 loc) · 2.01 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
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
package main
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/companieshouse/chs.go/log"
"github.com/companieshouse/penalty-payment-api/config"
"github.com/companieshouse/penalty-payment-api/dao"
"github.com/companieshouse/penalty-payment-api/handlers"
"github.com/gorilla/mux"
)
func main() {
namespace := "penalty-payment-api"
log.Namespace = namespace
const exitErrorFormat = "error configuring service: %s. Exiting"
cfg, err := config.Get()
if err != nil {
log.Error(fmt.Errorf(exitErrorFormat, err), nil)
return
}
// Create router
mainRouter := mux.NewRouter()
svc := dao.NewDAOService(cfg)
penaltyDetailsMap, err := config.LoadPenaltyDetails("assets/penalty_details.yml")
if err != nil {
log.Error(fmt.Errorf(exitErrorFormat, err), nil)
return
}
allowedTransactionsMap, err := config.GetAllowedTransactions("assets/penalty_types.yml")
if err != nil {
log.Error(fmt.Errorf(exitErrorFormat, err), nil)
return
}
handlers.Register(mainRouter, cfg, svc, penaltyDetailsMap, allowedTransactionsMap)
log.Info("Starting " + namespace)
h := &http.Server{
Addr: cfg.BindAddr,
Handler: mainRouter,
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt, syscall.SIGTERM)
// run server in new go routine to allow app shutdown signal wait below
go func() {
log.Info("starting server...", log.Data{"port": cfg.BindAddr})
err = h.ListenAndServe()
log.Info("server stopping...")
if err != nil && !errors.Is(http.ErrServerClosed, err) {
log.Error(err)
svc.Shutdown()
os.Exit(1)
}
}()
// wait for app shutdown message before attempting to close server gracefully
<-stop
log.Info("shutting down server...")
svc.Shutdown()
timeout := time.Duration(5) * time.Second
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
err = h.Shutdown(ctx)
if err != nil {
log.Error(fmt.Errorf("failed to shutdown server gracefully: [%v]", err))
} else {
log.Info("server shutdown gracefully")
}
}