-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
84 lines (69 loc) · 2.36 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
package main
import (
"context"
"errors"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/rs/zerolog/log"
healthcheckServer "github.com/wisdom-oss/go-healthcheck/server"
"microservice/internal"
"microservice/internal/config"
"microservice/internal/db"
"microservice/routes"
routeUtils "microservice/routes/utils"
"github.com/wisdom-oss/common-go/v3/middleware/gin/jwt"
)
// the main function bootstraps the http server and handlers used for this
// microservice
func main() {
// create a new logger for the main function
l := log.Logger
l.Info().Msgf("configuring %s service", internal.ServiceName)
// create the healthcheck server
hcServer := healthcheckServer.HealthcheckServer{}
hcServer.InitWithFunc(func() error {
// test if the database is reachable
return db.Pool.Ping(context.Background())
})
err := hcServer.Start()
if err != nil {
l.Fatal().Err(err).Msg("unable to start healthcheck server")
}
go hcServer.Run()
// prepare some scope requirers to make the route definition easiser
scopeRequirer := jwt.ScopeRequirer{}
scopeRequirer.Configure(internal.ServiceName)
r := config.PrepareRouter()
r.Use(routeUtils.ReadPageSettings)
r.GET("/", scopeRequirer.RequireRead, routes.PagedUsages)
r.GET("/consumer/*consumerID", scopeRequirer.RequireRead, routes.ConsumerUsages)
r.GET("/type/*usageTypeID", scopeRequirer.RequireRead, routes.TypedUsages)
r.GET("/municipal/*ars", scopeRequirer.RequireRead, routes.MunicipalUsages)
// create http server
server := &http.Server{
Addr: config.ListenAddress,
Handler: r,
}
l.Info().Msg("starting http server")
// Start the server and log errors that happen while running it
go func() {
if err := server.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
l.Fatal().Err(err).Msg("An error occurred while starting the http server")
}
}()
// Set up some the signal handling to allow the server to shut down gracefully
shutdownSignal := make(chan os.Signal, 1)
signal.Notify(shutdownSignal, syscall.SIGINT, syscall.SIGTERM)
// Block further code execution until the shutdown signal was received
l.Info().Msg("server ready to accept connections")
<-shutdownSignal
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
err = server.Shutdown(ctx)
if err != nil {
l.Fatal().Err(err).Msg("An error occurred while shutting down http server")
}
}